[R] Mean-replacing NAs in a 3d array
Eik Vettorazzi
E.Vettorazzi at uke.uni-hamburg.de
Fri Mar 20 12:05:20 CET 2009
Hi Tom,
it would have been nice (and it is in fact requested by the posting
guide) to give a running example instead of letting us construct your data.
Anyway, it wasn't too hard with
Xa<-array(1:12,dim=c(2,2,3))
Xa[c(2,6,8)]<-NA
#so next, create a vector for the colMeans with length 2*2*3, repeating
each mean 4 times
cM<-rep(colMeans(Xa,na.rm=TRUE,dims=2),each=dim(Xa)[1]*dim(Xa)[2])
#... and use the fact, that most r-objects have also an one-dimensional
index (which was used in the construction above as well)
Xa[is.na(Xa)]<-cM[is.na(Xa)]
hth.
T.R. Marshall schrieb:
> Hi all
>
> I have a 3d array containing missing values.
>
>
>> Xa
>>
> , , 1
>
> [,1] [,2]
> [1,] 1 3
> [2,] NA 4
>
> , , 2
>
> [,1] [,2]
> [1,] 5 7
> [2,] NA NA
>
> , , 3
>
> [,1] [,2]
> [1,] 9 11
> [2,] 10 12
>
> I want to replace the missing values with the mean, but the mean of each
> 'page' in the array (wrong terminology I'm sure). So - for the array
> above - [2,1,2] and [2,2,2] should both read '6', and [2,1,1] should be
> '2.66667'.
>
> I can obtain a vector of those means by:
>
>> colMeans(Xa,na.rm=TRUE,dims=2)
>>
> [1] 2.666667 6.000000 10.500000
>
> But what to do next?
>
> Help would be appreciated. Also I'm a noob to this mailing list so
> apologies if I've not given enough detail or failed to find the answer
> somewhere obvious.
>
> Best
> Tom Marshall, Universiteit van Amsterdam
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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