2

这是我的数据框:

library(zoo)
library(dplyr)

df <- data.frame(
  id = rep(1:4, each = 4), 
  status = c(
    NA, "a", "c", "a", 
    NA, "c", "c", "c",
    NA, NA, "a", "c",
    NA, NA, "c", "c"),
  otherVar = letters[1:16],
  stringsAsFactors = FALSE)

对于变量状态,我希望在组 (id) 中向后进行下一个观察。

df %>% group_by(id) %>% na.locf(fromLast = TRUE) %>% ungroup

但是,我只希望我的 "c" 向后携带,而不是 "a" 。

从变量状态:

不适用 “a” “c” “a” 不适用 “c” “c” “c” 不适用 不适用 “a” “c” 不适用 不适用 “c” “c”

我想得到:

不适用“a”“c”“a”“c”“c”“c”“c”不适用“a”“c”“c”“c”“c”“c”

分别:

data.frame(
  id = rep(1:4, each = 4), 
  status = c(
    NA, "a", "c", "a", 
    "c", "c", "c", "c",
    NA, NA, "a", "c",
    "c", "c", "c", "c"),
  otherVar = letters[1:16],
  stringsAsFactors = FALSE)

有没有办法做到这一点?

4

2 回答 2

3

应用后na.locf0检查每个位置,NA如果它现在a重新设置回NA。如果要覆盖status,请将第二status2=行替换为status = if_else(is.na(status) & status2 == "a", NA_character_, status2), status2 = NULL) %>%

library(dplyr)
library(zoo)

df %>% 
  group_by(id) %>% 
  mutate(status2 = na.locf0(status, fromLast = TRUE),
         status2 = if_else(is.na(status) & status2 == "a", NA_character_, status2)) %>%
  ungroup

给予:

# A tibble: 16 x 4
      id status otherVar status2
   <int> <chr>  <chr>    <chr>  
 1     1 <NA>   a        <NA>   
 2     1 a      b        a      
 3     1 c      c        c      
 4     1 a      d        a      
 5     2 <NA>   e        c      
 6     2 c      f        c      
 7     2 c      g        c      
 8     2 c      h        c      
 9     3 <NA>   i        <NA>   
10     3 <NA>   j        <NA>   
11     3 a      k        a      
12     3 c      l        c      
13     4 <NA>   m        c      
14     4 <NA>   n        c      
15     4 c      o        c      
16     4 c      p        c      
于 2018-05-07T16:25:12.583 回答
1

使用tidyr:fill基于创建dummyStatus列的解决方案。使用. fill_ 现在,在验证以下值应该是 . 之后,使用它来填充实际列中的值。dummyStatus.direction = "up"dummyStatusNAstatusc

library(dplyr)
library(tidyr)
df %>% group_by(id) %>%
    mutate(dummyStatus = status) %>%
    fill(dummyStatus, .direction = "up" ) %>%
    mutate(status = ifelse(is.na(status) & lead(dummyStatus)=="c","c",status)) %>%
    select(-dummyStatus) %>% as.data.frame()

  #    id status otherVar
  # 1   1   <NA>        a
  # 2   1      a        b
  # 3   1      c        c
  # 4   1      a        d
  # 5   2      c        e
  # 6   2      c        f
  # 7   2      c        g
  # 8   2      c        h
  # 9   3   <NA>        i
  # 10  3   <NA>        j
  # 11  3      a        k
  # 12  3      c        l
  # 13  4      c        m
  # 14  4      c        n
  # 15  4      c        o
  # 16  4      c        p

数据:

df <- data.frame(
  id = rep(1:4, each = 4), 
  status = c(
    NA, "a", "c", "a", 
    NA, "c", "c", "c",
    NA, NA, "a", "c",
    NA, NA, "c", "c"),
  otherVar = letters[1:16],
  stringsAsFactors = FALSE)
于 2018-05-07T16:22:57.430 回答