【问题标题】:How to crosstab 4 variables using tabyl in R如何在 R 中使用 tabyl 交叉表 4 个变量
【发布时间】:2021-03-04 16:45:30
【问题描述】:

我想按组g 交叉表变量xyz。我可以用 3 个变量 (tabyl(x,y,z)) 来做到这一点,但我想对 g 的每个值重复它。我试过group_by(g),但没用。

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(janitor)
#> 
#> Attaching package: 'janitor'
#> The following objects are masked from 'package:stats':
#> 
#>     chisq.test, fisher.test

df <- tibble(x = c(1, 2, 3, 3, 4, 3),
             y = c(1,1,1,2,2,2),
             z = c(1,2,1,1,2,2),
             g = c(1,1,1,1,2,2))

t <- df %>%
  tabyl(x,y,z)
t
#> $`1`
#>  x 1 2
#>  1 1 0
#>  2 0 0
#>  3 1 1
#>  4 0 0
#> 
#> $`2`
#>  x 1 2
#>  1 0 0
#>  2 1 0
#>  3 0 1
#>  4 0 1
Created on 2021-03-04 by the reprex package (v1.0.0)

【问题讨论】:

    标签: r crosstab janitor


    【解决方案1】:

    我们可以使用group_splitmap

    library(dplyr)
    library(janitor)
    library(purrr)
    df %>% 
         group_split(g) %>%
         map(~ .x %>% tabyl(x, y, z))
    

    【讨论】:

      猜你喜欢
      • 2014-09-29
      • 2020-07-01
      • 2018-07-06
      • 1970-01-01
      • 2021-09-17
      • 2012-01-07
      • 2018-01-05
      • 1970-01-01
      • 2022-06-14
      相关资源
      最近更新 更多