0

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?

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
ecologist1234
  • 225
  • 1
  • 8
  • `class(v.1[[1]])` is what? `array` or `matrix` or even a vector of numeric? Your two lines seem to do different things. Why do you need to iterate over the columns in the first line then disregard the columns in line 2? – Vlo Feb 23 '18 at 15:49
  • 5
    [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269) – Sotos Feb 23 '18 at 15:49
  • v.1[[1]] is numeric. I believe the 2nd code line is closer to what I'm after. There aren't really columns in v.1, since each element is a numeric list element, right? – ecologist1234 Feb 23 '18 at 15:53
  • Your question is still not well constructed. Lay out the problem before the sharing the code. Beyond the ["How to ask"](https://stackoverflow.com/help/how-to-ask) advice, you also need to start by stating the question in a way that focuses on what gap remains _after_ your research. Describe [step like these](https://hackernoon.com/how-to-debug-any-problem-ac6f8a867fae) that you have done thus far, for code, conditions, and errors. State 'obvious' context that you already know, [so that people understand what you have tried](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) – New Alexandria Feb 25 '18 at 03:57

1 Answers1

1

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)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63