Home > Blockchain >  R: How to count the number of occurrences of a value across multiple columns?
R: How to count the number of occurrences of a value across multiple columns?

Time:02-04

I am trying to count the number of times each variable occurs across two separate columns. Similar to:

var1    var2    var3
a       b       a
c       c       a
b       a       b

I want to know the number of times each variable occurs in the columns var1 and var2. The output should look something like

var   count
a     3
b     2
c     1

I have seen similar questions on stackoverflow but haven't seemed to find one that is what I am looking for.

CodePudding user response:

We may subset the columns, unlist to a vector and get the table in base R, stack it to a two column data.frame if needed

stack(table(unlist(df1[c("var1", "var2")])))[2:1]`

Or with packages, reshape to 'long' using pivot_longer and get the count

library(dplyr)
library(tidyr)
df1 %>%
    select(var1, var2) %>%
    pivot_longer(cols = everything(), names_to = NULL, values_to = 'var') %>%
    count(var, name = "count")
  •  Tags:  
  • Related