ID=1:6
V1=c(1,3,5,NA,NA,4)
V2=c(2,NA,5,NA,6,NA)
V3=c(NA,5,NA,NA,3,4)
V4=c(8,6,4,2,4,6)
dat=data.frame(ID,V1,V2,V3,V4)
dat
## ID V1 V2 V3 V4
## 1 1 1 2 NA 8
## 2 2 3 NA 5 6
## 3 3 5 5 NA 4
## 4 4 NA NA NA 2
## 5 5 NA 6 3 4
## 6 6 4 NA 4 6
print(apply(dat[,2:5],2,mean,na.rm=T),digits=3) #mean column
## V1 V2 V3 V4
## 3.25 4.33 4.00 5.00
library(zoo)
na.aggregate(dat,FUN = mean) # May replace by median
## ID V1 V2 V3 V4
## 1 1 1.00 2.000000 4 8
## 2 2 3.00 4.333333 5 6
## 3 3 5.00 5.000000 4 4
## 4 4 3.25 4.333333 4 2
## 5 5 3.25 6.000000 3 4
## 6 6 4.00 4.333333 4 6
dat1=dat[,2:5];
dat1$RowM=apply(dat1,1,mean,na.rm=T) #mean column
dat1_cv=t(dat1)
dat2=t(na.aggregate(dat1_cv))
dat2
## V1 V2 V3 V4 RowM
## [1,] 1.000000 2.000000 3.666667 8 3.666667
## [2,] 3.000000 4.666667 5.000000 6 4.666667
## [3,] 5.000000 5.000000 4.666667 4 4.666667
## [4,] 2.000000 2.000000 2.000000 2 2.000000
## [5,] 4.333333 6.000000 3.000000 4 4.333333
## [6,] 4.000000 4.666667 4.000000 6 4.666667
library(randomForest)
print(apply(dat[,2:5],2,median,na.rm=TRUE),digits=3) #mean column
## V1 V2 V3 V4
## 3.5 5.0 4.0 5.0
dat
## ID V1 V2 V3 V4
## 1 1 1 2 NA 8
## 2 2 3 NA 5 6
## 3 3 5 5 NA 4
## 4 4 NA NA NA 2
## 5 5 NA 6 3 4
## 6 6 4 NA 4 6
na.roughfix(dat)
## ID V1 V2 V3 V4
## 1 1 1.0 2 4 8
## 2 2 3.0 5 5 6
## 3 3 5.0 5 4 4
## 4 4 3.5 5 4 2
## 5 5 3.5 6 3 4
## 6 6 4.0 5 4 6
x=c(20,30,50,NA,NA,70)
na.locf(x,fromLast = FALSE)
## [1] 20 30 50 50 50 70
na.locf(x,fromLast = TRUE)
## [1] 20 30 50 70 70 70
x=c(20,30,50,NA,NA,70)
print(na.approx(x),digits=2)
## [1] 20 30 50 57 63 70
dat
## ID V1 V2 V3 V4
## 1 1 1 2 NA 8
## 2 2 3 NA 5 6
## 3 3 5 5 NA 4
## 4 4 NA NA NA 2
## 5 5 NA 6 3 4
## 6 6 4 NA 4 6
dat_rep1=na.approx(dat);dat_rep1
## ID V1 V2 V3 V4
## [1,] 1 1.000000 2.0 NA 8
## [2,] 2 3.000000 3.5 5.000000 6
## [3,] 3 5.000000 5.0 4.333333 4
## [4,] 4 4.666667 5.5 3.666667 2
## [5,] 5 4.333333 6.0 3.000000 4
## [6,] 6 4.000000 NA 4.000000 6
dat_rep1 may need more replacing by na.locf function
dat_rep2=na.locf(dat_rep1,fromLast = FALSE)
dat_rep3=na.locf(dat_rep2,fromLast = TRUE)
dat_rep3
## ID V1 V2 V3 V4
## [1,] 1 1.000000 2.0 5.000000 8
## [2,] 2 3.000000 3.5 5.000000 6
## [3,] 3 5.000000 5.0 4.333333 4
## [4,] 4 4.666667 5.5 3.666667 2
## [5,] 5 4.333333 6.0 3.000000 4
## [6,] 6 4.000000 6.0 4.000000 6