Home > Software design >  How to get the sum of combinations of variables of 2 columns in a tibble in r
How to get the sum of combinations of variables of 2 columns in a tibble in r

Time:11-23

     1       2     3       4              5
 1  2013     A     B      513            513         
 2  2013     B     A      533            524         
 3  2013     B     A      541            540         
 4  2013     B     A      544            532        
 5  2013     E     B      554            540       
 6  2014     F     B      557            558      
 7  2014     F     A      553            604       
     

I have a tibble like that. How I can get the sum of every combination of the columns 2 and 3? So that I get 1 for A and B, 3 for B and A, 1 for E and B and so on.

CodePudding user response:

Group those two variables and summarise. Easy to do with tidyverse, although I'd change the names of the columns to text first.

library(tidyverse)

df %>%
 group_by(col2, col3) %>%
 summarise(count = n())

  • Related