dplyr to combine multiple result

Viewed 69

May I know if there are any faster solution to union all of the data that we count using dplyr in R? as you can see below my im trying to combine all 3 count to one dataframe but failed as I dont know how to union the data from my results

check = data.frame(gender = c('M','F','M','F','F'),
              place = c('US', 'Non-US', 'US', 'US', 'US'),
              work = c('IT', 'Non-IT', 'Non-IT', 'Non-IT', 'IT'),
        checkup = c('Yes', 'Yes', 'No', 'Yes', 'No'))

library(dplyr)
attach(check)
gender = count(check ,gender,checkup)
place = count(check ,place ,checkup)
work = count(check ,work ,checkup)

and as you can see the output are

enter image description here

my desired output should be like this

enter image description here

3 Answers

It would be easier if you get the data in long format and use count -

library(dplyr)
library(tidyr)

check %>% pivot_longer(cols = -checkup) %>% count(name, value, checkup)

#   name   value  checkup     n
#   <chr>  <chr>  <chr>   <int>
# 1 gender F      No          1
# 2 gender F      Yes         2
# 3 gender M      No          1
# 4 gender M      Yes         1
# 5 place  Non-US Yes         1
# 6 place  US     No          2
# 7 place  US     Yes         2
# 8 work   IT     No          1
# 9 work   IT     Yes         1
#10 work   Non-IT No          1
#11 work   Non-IT Yes         2

A data.table option

> unique(melt(setDT(check), id.var = "checkup")[, n := .N, checkup:value])
    checkup variable  value n
 1:     Yes   gender      M 1
 2:     Yes   gender      F 2
 3:      No   gender      M 1
 4:      No   gender      F 1
 5:     Yes    place     US 2
 6:     Yes    place Non-US 1
 7:      No    place     US 2
 8:     Yes     work     IT 1
 9:     Yes     work Non-IT 2
10:      No     work Non-IT 1
11:      No     work     IT 1

Using base R with ftable

subset(as.data.frame(ftable(cbind(stack(check[1:3]), rep(check$checkup, 3)))), Freq != 0)
Related