R:如何在特定条件下替换NA值

时间:2018-09-24 02:49:56

标签: r

每个人。我想将NA值替换为对于同一参与者不是NA的值。我试过了,但是它返回了原始的df,我不知道发生了什么。

df = data.frame(block = c('1',NA,NA,'2',NA,NA,'3',NA,NA),
                subject = c('31','31','31','32','32','32','33','33','33'))

df[df$subject == 1 & is.na(df$block)] = df[df$subject == 31 &!is.na(df$block)]

# define a for loop with from 1 to n 
for (i in 1: length(unique(df$subject))){
    subjects

    # replace the block with NA in block that is not NA for the same participant    
    df[df$subject == i & is.na(df$block)] = df[df$subject == i & !is.na(df$block)]  
}

这就是我想要得到的。  enter image description here

1 个答案:

答案 0 :(得分:0)

使用dplyr和zoo库,我将block列中的NA值替换为先前的非NA行值:

library(dplyr)
library(zoo)

df2 <- df %>%
    do(na.locf(.))

最终结果如下:

df2

  block subject
1     1      31
2     1      31
3     1      31
4     2      32
5     2      32
6     2      32
7     3      33
8     3      33
9     3      33