[R] replace NA's with row means for specific columns
David L Carlson
dcarlson at tamu.edu
Tue Nov 3 16:30:22 CET 2015
This should be a bit quicker since it just loops through the column blocks:
> Zdf <- structure(list(ID = structure(1:4, .Label = c("b", "c", "d",
+ "e"), class = "factor"), A1 = c(4L, 4L, NA, 4L), A2 = c(5L, 5L,
+ 5L, 5L), A3 = c(NA, 1L, 1L, 4L), B1 = c(2L, NA, 1L, 5L), B2 = c(NA,
+ 3L, NA, NA), B3 = c(4L, 4L, 4L, 4L), C1 = c(5L, 5L, 5L, 5L),
+ C2 = c(1L, 1L, 1L, 1L), C3 = c(3L, 3L, 3L, 3L), C4 = c(NA,
+ 2L, 2L, 2L)), .Names = c("ID", "A1", "A2", "A3", "B1", "B2",
+ "B3", "C1", "C2", "C3", "C4"), class = "data.frame", row.names = c(NA,
+ -4L))
>
> Zdf
ID A1 A2 A3 B1 B2 B3 C1 C2 C3 C4
1 b 4 5 NA 2 NA 4 5 1 3 NA
2 c 4 5 1 NA 3 4 5 1 3 2
3 d NA 5 1 1 NA 4 5 1 3 2
4 e 4 5 4 5 NA 4 5 1 3 2
>
> A <- grep("^A", colnames(Zdf))
> B <- grep("^B", colnames(Zdf))
> C <- grep("^C", colnames(Zdf))
>
> for (i in list(A, B, C)) {
+ mn <- rowMeans(Zdf[, i], na.rm=TRUE)
+ miss <- which(is.na(Zdf[, i]), arr.ind=TRUE)
+ Zdf[, i][miss]<- mn[miss[, 1]]
+ }
>
> Zdf
ID A1 A2 A3 B1 B2 B3 C1 C2 C3 C4
1 b 4 5 4.5 2.0 3.0 4 5 1 3 3
2 c 4 5 1.0 3.5 3.0 4 5 1 3 2
3 d 3 5 1.0 1.0 2.5 4 5 1 3 2
4 e 4 5 4.0 5.0 4.5 4 5 1 3 2
-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352
-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Jim Lemon
Sent: Monday, November 2, 2015 5:33 PM
To: Zahra
Cc: r-help mailing list
Subject: Re: [R] replace NA's with row means for specific columns
Hi again,
Small typo in line 5 - should be
replace_NAs<-function(x,group_lab=c("A","B","C")) {
for(lab in group_lab) {
indices<-grep(lab,names(x),fixed=TRUE)
na_indices<-is.na(x[indices])
if(any(na_indices))
x[indices][na_indices]<-rowMeans(x[indices],na.rm=TRUE)
}
return(x)
}
Jim
[[alternative HTML version deleted]]
______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list