[R] Subsetting array (NA:s)

Marc Schwartz marc_schwartz at comcast.net
Thu Jan 10 17:37:36 CET 2008


Lauri Nikkinen wrote:
> Hi R-users,
> 
> I have an array similar to this:
> 
> tmp <- array(1:6, c(2,3,3))
> n1 <- c("one", "two")
> n2 <- c("three", "four", "five")
> n3 <- c("six", "seven", "eight")
> dimnames(tmp) <- list(n1, n2, n3)
> tmp[1,,1] <- NA
> tmp[1,3,2] <- NA
> tmp[2,,3] <- NA
> tmp
> 
> How to subset !is.na(x) rows resulting
> 
> , , six
> 
>     three four five
> two     2    4    6
> 
> , , seven
> 
>     three four five
> one     1    3   NA
> two     2    4    6
> 
> , , eight
> 
>     three four five
> one     1    3    5
> 
> I have tried something like
> 
> tmp[!apply(is.na(tmp), 1, all),,]
> 
> with negative results.
> 
> Thanks
> -Lauri

There might be an easier way, but here is one approach.  The problem
that you will have is that you will not be returning an object with
"consistent dimensions". Thus, you will end up with a list, not an array.


> apply(tmp, 3,
        function(i) i[apply(i, 1,
                            function(x) !all(is.na(x))), ,
                      drop = FALSE])
$six
    three four five
two     2    4    6

$seven
    three four five
one     1    3   NA
two     2    4    6

$eight
    three four five
one     1    3    5



HTH,

Marc Schwartz




More information about the R-help mailing list