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 [[alternative HTML version deleted]]
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? ThanksPresuming 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. HTH, Marc Schwartz
x <- list(integer(0),1,2) x[sapply(x, length) > 0] ------------------------------------------------- Remko Duursma Post-Doctoral Fellow Centre for Plant and Food Science University of Western Sydney Hawkesbury Campus Richmond NSW 2753 Dept of Biological Science Macquarie University North Ryde NSW 2109 Australia Mobile: +61 (0)422 096908 On Fri, Feb 13, 2009 at 3:07 PM, Stuart Jaffe <stuart.jaffe at gmail.com> 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 > > [[alternative HTML version deleted]] > > ______________________________________________ > 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. >
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