I want to convert NA
s to a certain value, based on the given variable value for that specific ID. Sample query: df1 ---> df2
df1 = data.frame(ID=c(1,1, 1, 1, 2,2,2,2,3,3,3,3),WHR=c(0.8,NA, NA, NA,1.0, NA, NA,NA,1.1, NA, NA, NA))
df2=data.frame(ID=c(1,1, 1, 1, 2,2,2,2,3,3,3,3),WHR=c(0.8,0.8, 0.8, 0.8,1.0, 1.0,1.0,1.0, 1.1, 1.1,1.1,1.1))`
What I tried
R fill in NA with previous row value with condition:
library(xts)
df1[,WHR:=na.locf("WHR", fromlast=TRUE, by = ID)`
Got error:
could not find function ":=";
I used this code because I have hundreds of ID values and I would like an automatic code that changes NA
s in a particular column based on ID.
How can I convert df1
to df2
? (pls explain your code as well, so it may help other beginner users). Thank you!