I have a data frame with NAs and I want to replace the NAs with row means
c1 = c(1,2,3,NA) c2 = c(3,1,NA,3) c3 = c(2,1,3,1) df = data.frame(c1,c2,c3) >
My solution is
rwmns = rowMeans(df,na.rm=TRUE) df$c1[is.na(df$c1)] = rwmns[is.na(df$c1)] df$c2[is.na(df$c2)] = rwmns[is.na(df$c2)] df$c3[is.na(df$c3)] = rwmns[is.na(df$c3)] > df c1 c2 c3 1 1 3 2 2 2 1 1 3 3 3 3 4 2 3 1
Is there a more elegant way, especially when someone has many columns?