[R] removing NA from multidmension arrays

Peter Ehlers ehlers at ucalgary.ca
Fri Mar 30 20:31:31 CEST 2012


On 2012-03-30 10:15, Rui Barradas wrote:
> Hello,
>
>
> Bcampbell99 wrote
>>
>> Hi:
>>
>> I'm having some difficulty properly subscripting a function to remove
>> complete NA rows from a R array object.  Could someone please suggest how
>> best
>> to script this out?
>>
>> Data structure:
>>
>> X is an array with 3 dimensions (replicates, Species, Sites)
>> replicates: 1 to 6 but ragged...not all sites equal
>>
>>
>>
>> ,,Site1
>>
>> 	Sp1	Sp2	Sp3...	Sp50
>> 1	5	4	3		2
>> 2	3	0	0		1
>> 3	NA	NA	NA		NA
>> 4	NA	NA	NA		NA
>> 5	NA	NA	NA		NA
>> 6	NA	NA	NA		NA
>>
>>
>>
>> ,,Site2
>>
>> 	Sp1	Sp2	Sp3...	Sp50
>> 1	5	4	3		2
>> 2	3	0	0		1
>> 3	1	1	0		0
>> 4	NA	NA	NA		NA
>> 5	NA	NA	NA		NA
>> 6	NA	NA	NA		NA
>>
>>
>> ,,Site3
>>
>> 	Sp1	Sp2	Sp3...	Sp50
>> 1	5	4	3		2
>> 2	3	0	0		1
>> 3	1	1	0		0
>> 4	5	4	3		2
>> 5	3	0	0		1
>> 6	1	1	0		0
>>
>> Most appreciatively:
>>
>> Brian Campbell
>>
>
> Try
>
> # Make up some data
> x<- array(1:24, c(4, 3, 2))
> x[3,, 1]<- NA
> x[3:4,, 2]<- NA
> x
>
> apply(x, 3, function(mat)
> 		do.call(rbind, apply(mat, 1, function(y) if(any(!is.na(y))) y)))
>
>
> Hope this helps,
>
> Rui Barradas
>

Or use complete.cases():

   apply(x, 3, function(mat) mat[complete.cases(mat), ])

Peter Ehlers

>
> --
> View this message in context: http://r.789695.n4.nabble.com/removing-NA-from-multidmension-arrays-tp4519369p4519750.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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