r - Replace NA by row with the row mean -
i have following data-frame:
i1<-c(5,4,3,4,5) i2<-c(4,na,na,5,3) i3<-c(na,4,4,4,5) i4<-c(3,5,5,na,2) dat<-as.data.frame(cbind(i1,i2,i3,i4)) dat i1 i2 i3 i4 1 5 4 na 3 2 4 na 4 5 3 3 na 4 5 4 4 5 4 na 5 5 3 5 2
my goal replace na
row mean get:
> dat i1 i2 i3 i4 1 5 4.0000 4 3.0000 2 4 4.3333 4 5.0000 3 3 4.0000 4 5.0000 4 4 5.0000 4 4.3333 5 5 3.0000 5 2.0000
i have following code:
dat1<- which(is.na(dat), arr.ind=true) dat[dat1] <- rowmeans(dat, na.rm=true)[dat1[,1]]
which yield desired result; however, wondering if there better way this, , keep both row , column names (rows have names in final product). thank you.
try
(is.na(dat))*rowmeans(dat, na.rm=true)[row(dat)] + replace(dat, is.na(dat), 0) # i1 i2 i3 i4 #1 5 4.000000 4 3.000000 #2 4 4.333333 4 5.000000 #3 3 4.000000 4 5.000000 #4 4 5.000000 4 4.333333 #5 5 3.000000 5 2.000000
Comments
Post a Comment