0

I am trying to force some list objects (e.g. 4 tables of frequency count) into a matrix by doing rbind. However, they have uneven columns (i.e. some range from 2 to 5, while others range from 1:5). I want is to display such that if a table does not begin with a column of 1, then it displays NA in that row in the subsequent rbind matrix. I tried the approach below but the values repeat itself in the row rather than displaying NAs if is does not exist. I considered rbind.fill but it requires for the table to be a data frame. I could create some loops but in the spirit of R, I wonder if there is another approach I could use?

# Example
a <-  sample(0:5,100, replace=TRUE)
b <- sample(2:5,100, replace=TRUE)
c <-  sample(1:4,100, replace=TRUE)
d <- sample(1:3,100, replace=TRUE)

list <- list(a,b,c,d)
table(list[4])

count(list[1])
matrix <- matrix(ncol=5)
lapply(list,(table))

do.call("rbind",(lapply(list,table)))
Sam
  • 261
  • 2
  • 12
  • Maybe the answers [here](http://stackoverflow.com/questions/17308551/do-callrbind-list-for-uneven-number-of-column?rq=1) can help. – Sraffa Sep 11 '16 at 04:36

1 Answers1

0

When I have a similar problem, I include all the values I want in the vector and then subtract one from the result

table(c(1:5, a)) - 1

This could be made into a function

table2 <- function(x, values, ...){
  table(c(x, values), ...) - 1
}

Of course, this will give zeros rather than NA

Richard Telford
  • 9,558
  • 6
  • 38
  • 51