1

everyone. I want to replace the NA value with value which is not NA for the same participants. I tried this, but it return the original df, i don't know what happened.

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)]  
}

Here is what i want to get. enter image description here

Eacher
  • 13
  • 3

1 Answers1

0

Using the dplyr and the zoo library, I replaced the NA values in the block column with the previous non-NA row values:

library(dplyr)
library(zoo)

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

The end result looks as follow:

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
DTYK
  • 1,098
  • 1
  • 8
  • 33