gpt4 book ai didi

r - 如何在R中使用tabyl交叉表4个变量

转载 作者:行者123 更新时间:2023-12-04 08:00:52 28 4
gpt4 key购买 nike

我想交叉表变量 x , y , z按组 g .我可以用 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)

最佳答案

我们可以使用 group_splitmap

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

关于r - 如何在R中使用tabyl交叉表4个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66479381/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com