1

In the following case I want to replace the NA with the corresponding z column value. How do I assign it?

df<-data.frame(x=c(1,2,3,4,5,NA,7,NA,9,10),
               z=c(1:10))

With this code I the NA is replaced with starting z value (1 and 2) and I need (6 and 8).

df$x[is.na(df$x)] <- (df$z)
sler
  • 55
  • 4

1 Answers1

1

We can use same the logic on the rhs

df$x[is.na(df$x)] <- df$z[is.na(df$x)]
akrun
  • 674,427
  • 24
  • 381
  • 486