Home > Software engineering >  How to count multiple column in R
How to count multiple column in R

Time:12-14

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

CodePudding user response:

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)

CodePudding user response:

Iterate using purrr::map() to dplyr::count() by each column, then use purrr::reduce() to dplyr::left_join() all the result dataframes together.

library(dplyr)
library(purrr)
set.seed(13)

counts <- map(
  names(df),
  ~ count(df, score = .data[[.x]], name = .x)
)

reduce(counts, left_join)
  score a b c d
1     0 4 5 3 2
2     1 4 1 2 5
3     2 2 4 5 3
  •  Tags:  
  • r
  • Related