I want to replace my NA values from a matrix acquired by :
read.table(…)
Those values should be the mean of the corresponding row.
I.e, the following row of the table :
1 2 1 NA 2 1 1 2
would become
1 2 1 1.43 2 1 2
Thank you.
Here's some sample data.
m <- matrix(1:16, nrow=4)
m[c(1,4,6,11,16)] <- NA
And here's how I'd fill in missings with the row means.
k <- which(is.na(m), arr.ind=TRUE)
m[k] <- rowMeans(m, na.rm=TRUE)[k[,1]]
Your data will be in a data.frame
; you'll have to convert to a matrix first using as.matrix
. You may or may not want to leave it in that format; to convert back use as.data.frame
.
[<-.data.frame
(*tmp*
, k, value = c(3.67857142857143, 3.34375, : only logical matrix subscripts are allowed in replacement
as.matrix
), then do it, then convert back (as.data.frame
).
Aug 3, 2011 at 17:37
x[is.na(x)] <- mean(x, na.rm=TRUE) # for vectors or for a matrix as a whole
t( apply(x, 1, function(xv) { xv[is.na(xv)] <-
mean(xv, na.rm=TRUE)
return(xv)}
) ) # for a row-oriented sol'n
a = c(NA, 1, 2, 3, 10)
a[which(is.na(a)==TRUE)] = mean(a,na.rm = T)
which
is not necessary either, since you can index vectors either by a vector of length <= length(a)
or by a vector of length length(a)
containing TRUEs and FALSEs (or 0/1's which get coerced to TRUE/FALSE). Finally, avoid using T and F for TRUE and FALSE, since they can get overwritten.
Aug 2, 2011 at 20:32
NA
within the variable.read.table()
returns a data.frame. Are you talking about a data frame or a proper matrix?