Home > database >  How to tabulate three variables with tables in R
How to tabulate three variables with tables in R

Time:09-23

I am trying to tabulate df dataframe using three variables using tabular from the tablespackage. The format of the result is OK but I don't understand why the values are all equal to 1 instead of using the values variable (frequency).

library(tidyverse)
library(tables)

df <- tibble(UT = c(rep(1, 9), rep(2,9)),
             sex = rep(c(rep('MF', 3), rep('M', 3), rep('F', 3)),2),
             age = rep(c('a','b','c'), 6),
             values = c(1:18))

df <- df %>%
  mutate(across(c(UT, sex, age), as.factor))


tabular(UT ~ (age * sex), data=df)
#>                               
#>     age                       
#>     a        b        c       
#>     sex      sex      sex     
#>  UT F   M MF F   M MF F   M MF
#>  1  1   1 1  1   1 1  1   1 1 
#>  2  1   1 1  1   1 1  1   1 1
Created on 2022-09-22 with reprex v2.0.2

CodePudding user response:

Perhaps this helps

tabular((values)*(sum) ~ (UT *age *sex), data = df)

-output

     UT                                                      
            1                          2                            
            age                        age                          
            a        b        c        a         b         c        
            sex      sex      sex      sex       sex       sex      
            F   M MF F   M MF F   M MF F   M  MF F   M  MF F   M  MF
 values sum 7   4 1  8   5 2  9   6 3  16  13 10 17  14 11 18  15 12

Or in base R with xtabs

xtabs(values ~ ., df)

CodePudding user response:

I found a solution using pivottabler package.

library(pivottabler)
qhpvt(df,"UT",  c("age", "sex"), "sum(values)", totals="NONE")
  • Related