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 multiple columns

everyone.
Here’s the problem:

Column1  Column2
da          fa
fa          da
ra          da
ta          ta

I need to count how many times each string appears in both columns: I mean, "da" appears 1 time in Column1 and 2 times in Column2, so I need the count of 3. Ps.: I can’t stack them, because it will generate new rows with null values in my dataframe.

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

>Solution :

Using pivot_longer

library(dplyr)
library(tidyr)

df1 %>% pivot_longer(cols = everything()) %>% count(value)
# A tibble: 4 × 2
  value     n
  <chr> <int>
1 da        3
2 fa        2
3 ra        1
4 ta        2
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