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

Count observations by group in a list of dataframes in r

Problem

I have a list of data frames. All of the dataframes have the same column names, but different numbers of rows. One column, called pred has the following four factors.

  1. Apple
  2. Cherry
  3. Orange
  4. Pear

I wish to count how many rows are ‘apple’, ‘cherry’ etc.

If I single out one dataframe (dataframe1), and perform the counts using:

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

count(dataframe1, pred)

I get the desired output:

pred                     n 
<fctr>                 <int>
Apple                   25          
Orange                  11          
Pear                    11          
Cherry                  12  

This is how I would like the output for mutliple dataframes that are contained within a list. How can this be achieved? I have tried various options using the dyplr package, but tend to get the error.

'Error in UseMethod("count") : no applicable method for 'count' applied to an object of class "list"'

>Solution :

If all data.frame have the same columns you can use this:

library(dplyr)


data1 <-data.frame(pred = sample(c("Apple","Cherry","Orange","Pear"),100,replace = TRUE))
data2 <-data.frame(pred = sample(c("Apple","Cherry","Orange","Pear"),100,replace = TRUE))
data3 <-data.frame(pred = sample(c("Apple","Cherry","Orange","Pear"),100,replace = TRUE))


list_of_dataframes <- list(data1,data2,data3)


bind_rows(list_of_dataframes,.id = "data") %>% 
  count(data,pred)
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