Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Counting values in list and creating new colums containing counts

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading