Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count multiple column in R

Tags:

dataframe

r

I'm trying to count the number of 0:2 in multiple columns of my data. Here is a sample. Thank for everyone.

df <- data_frame(
  a = sample(0:2, 10, replace=T), 
  b = sample(0:2, 10, replace=T), 
  c = sample(0:2, 10, replace=T), 
  d = sample(0:2, 10, replace=T), 
)

I want to got like this output

score a b c d
0 2 4 3 4
1 2 5 2 1
2 6 1 5 5
like image 661
user20137369 Avatar asked Oct 18 '25 12:10

user20137369


1 Answers

Code

library(tidyr)
library(dplyr)

df %>% 
  pivot_longer(cols = everything(),values_to = "score") %>% 
  count(name,score) %>% 
  pivot_wider(names_from = name,values_from = n,values_fill = 0)
like image 64
Vinícius Félix Avatar answered Oct 20 '25 02:10

Vinícius Félix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!