[R] R Help
Marc Schwartz
marc_schwartz at comcast.net
Fri Feb 13 05:38:29 CET 2009
on 02/12/2009 10:17 PM Marc Schwartz wrote:
> on 02/12/2009 10:07 PM Stuart Jaffe wrote:
>> Hi,
>> I have a list of numbers (classified as a list) that contains integer(0)
>> empty vectors. How do I convert those integer(0) into NAs? Thanks
>
> Presuming that you are referring to a list along the lines of:
>
> L <- list(1:5, integer(0), 2:4, integer(0), integer(0), 3:7)
>
>> L
> [[1]]
> [1] 1 2 3 4 5
>
> [[2]]
> integer(0)
>
> [[3]]
> [1] 2 3 4
>
> [[4]]
> integer(0)
>
> [[5]]
> integer(0)
>
> [[6]]
> [1] 3 4 5 6 7
>
>
>
> You could use:
>
>> lapply(L, function(x) if (length(x) == 0) NA else x)
> [[1]]
> [1] 1 2 3 4 5
>
> [[2]]
> [1] NA
>
> [[3]]
> [1] 2 3 4
>
> [[4]]
> [1] NA
>
> [[5]]
> [1] NA
>
> [[6]]
> [1] 3 4 5 6 7
>
>
> The key is that integer(0) has length 0.
Here is one more option, setting the individual elements to NA, rather
than copying them:
is.na(L) <- which(sapply(L, length) == 0)
See ?is.na
Also, if you wished to remove the integer(0) based elements, you can set
them to NULL:
L[which(sapply(L, length) == 0)] <- NULL
> L
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] 2 3 4
[[3]]
[1] 3 4 5 6 7
Marc
More information about the R-help
mailing list