Jimbou - 19 days ago 5
R Question

# Merge or c*rbind a list of table results in a data.frame & adding missing values

My google technique was not successful today, so I ask a new question:

I have a matrix of values

`c(0, 2, 3)`
:

``````> a
1 2 3 4 5 6 7 8 9 10
1  2 2 2 2 3 3 3 3 2  2
2  2 2 2 2 3 3 3 3 2  2
3  0 2 2 2 2 2 2 2 0  2
4  0 2 2 2 2 2 2 2 0  2
5  2 2 2 2 3 3 3 3 2  2
6  2 2 2 2 2 2 2 2 2  2
7  2 2 2 2 2 2 2 2 2  2
8  2 2 2 2 2 2 2 2 2  2
9  2 2 2 2 3 3 3 3 2  2
10 2 2 2 2 2 2 2 2 2  2
``````

I calculate for each row the occurence of these values using
`apply`

``````res <- apply(a, 1, table)
res[1:3]
[[1]]

2 3
6 4

[[2]]

2 3
6 4

[[3]]

0 2
2 8
``````

Now I try to merge the list to one data.frame by filling up the missing values in some slots by
`0`
or
`NA`
and optionally with the name. My goal is a simple function using
`do.call`
or something like
`Reduce(function(...) merge(..., all=TRUE), res)`
. But both approaches are not working.

Expected output would be:

``````final[1:3, ]
0 2 3
[1,] 0 6 4
[2,] 0 6 0
[3,] 2 8 8
``````

and the data:

``````structure(list(`1` = c(2, 2, 0, 0, 2, 2, 2, 2, 2, 2), `2` = c(2,
2, 2, 2, 2, 2, 2, 2, 2, 2), `3` = c(2, 2, 2, 2, 2, 2, 2, 2, 2,
2), `4` = c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2), `5` = c(3, 3, 2, 2,
3, 2, 2, 2, 3, 2), `6` = c(3, 3, 2, 2, 3, 2, 2, 2, 3, 2), `7` = c(3,
3, 2, 2, 3, 2, 2, 2, 3, 2), `8` = c(3, 3, 2, 2, 3, 2, 2, 2, 3,
2), `9` = c(2, 2, 0, 0, 2, 2, 2, 2, 2, 2), `10` = c(2, 2, 2,
2, 2, 2, 2, 2, 2, 2)), row.names = c(NA, -10L), class = "data.frame", .Names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10"))
``````

You could use `smartbind` from `gtools` package:
``````library(gtools)