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 use dplyr to count number?

I have used pivot_longer to transform my dataset as

  name   value
  <chr>  <dbl>
1 A      3
2 B      2
3 C      3
4 A      2
5 B      2
6 C      3

I want to count value of each name as

value   A  B  C
1       0  0  0
2       1  2  0  
3       1  0  2

I wonder how to use dplyr to ahieve it.

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 :

Use pivot_wider:

library(tidyr)
df %>% 
  pivot_wider(names_from = name, values_from = name,
              values_fn = length, values_fill = 0) %>% 
  complete(value = 1:3) %>% 
  replace(is.na(.), 0)

# A tibble: 3 × 4
  value     A     B     C
  <int> <int> <int> <int>
1     1     0     0     0
2     2     1     2     0
3     3     1     0     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