Search code examples
rlistfrequencydata-manipulation

Frequency table of values from list with missing values in R


I have a large list object in R that gives the values of raster cells within each of many polygons that fall on top of the raster. For those not used to spatial data, it is just a list with a few hundred elements, each of which has many integer values that range from 0-16. I need a frequency table showing the number of occurrences of each value in each list element (polygon). So far I've tried the following two approaches, where v.1 is the list.

v.1 <- list(c(1,1,2,2,3,4), c(2,2,2,4,5,5,6,9, NA))

 w=lapply(v.1, function(x) apply(x, 2, table))

which returns "Error in apply(x, 2, table) : dim(X) must have a positive length" and

f <- do.call(rbind, lapply(v.1, FUN = function(x) { return( table(x)) }))

which returns "Warning message: In (function (..., deparse.level = 1) : number of columns of result is not a multiple of vector length (arg 2)."

The problem, I think, is that not all values (0-16 in the real data set) appear in each list element. How can I get around this to create a correct frequency table?


Solution

  • Example data:

    v <- list(c(1,1,2,2,3,4), c(2,2,2,4,5,5,6,9, NA))
    

    You can do

    w <- lapply(v, table)
    

    But to combine things, I would do

    w <- lapply(1:length(v), function(i)  cbind(id=i, data.frame(table(v[[i]])))  )
    

    Followed by

    x <- do.call(rbind, w)