I have a list that of values that I would like to count the first column of each element and create a new dataframe with the counts.
Here is an example:
List:
my_list <- list(cbind(c("a", "b", "a"),c("R", "B", "R")),
cbind(),
cbind(c("a", "a", "c","b"),c("B", "R", "R","B")))
> my_list
[[1]]
[,1] [,2]
[1,] "a" "R"
[2,] "b" "B"
[3,] "a" "R"
[[2]]
NULL
[[3]]
[,1] [,2]
[1,] "a" "B"
[2,] "a" "R"
[3,] "c" "R"
[4,] "b" "B"
Desired Output in a dataframe:
"a" "b" "c"
[1,] 2 1 0
[2,] 0 0 0
[3,] 2 1 1
CodePudding user response:
Convert the list elements to factor
with levels
specified as 'a', 'b', 'c' and get the frequency count with table
t(sapply(my_list, \(x) table(factor(x, levels = c("a", "b", "c")))))
a b c
[1,] 2 1 0
[2,] 0 0 0
[3,] 2 1 1