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

How to count number of values in columns based on a category in R?

Suppose we have a data frame df like

book_id book_category book_word_hi book_word_bye book_word_yes
1       drama         3            0             4
2       action        1            4             5
3       drama         5            3             2

I would like to count the number of values within the book_word columns and sum them in a table for each book_category.

So the output here should look something like:

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

drama: 17 
action: 10

Does anyone know how to do this?

>Solution :

This is a short and simple one-liner in base R, without requiring any additional packages.

tapply(rowSums(df[3:5]), df[2], sum)
#> book_category
#> action  drama 
#>     10     17 
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