迭代 R 中交叉表的指定列 [英] Iterate over specified columns for crosstabs in R

查看:28
本文介绍了迭代 R 中交叉表的指定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在同一个数据集中运行几十个交叉表,并使用一组结果变量.我有一个函数可以提供我想要的交叉表:

I am looking to run a couple of dozen crosstabs within the same dataset and with a set outcome variable. I have a function that gives me the crosstabs I want:

second_table = function(dat, variable1, variable2){
  
  dat %>% 
  tabyl({{variable1}}, {{variable2}}, show_na = FALSE) %>% 
  adorn_percentages("row") %>% 
  adorn_pct_formatting(digits = 1) %>% 
  adorn_ns() 
  
}

以 mtcars 数据集为例,该函数为我提供了我想要的单个变量:

Using the mtcars dataset as an example, the function gives me what I want for a single variable:

cars = datasets::mtcars

second_table(cars, cyl, vs)

不过,我真正想要的是创建许多这样的表,其中 dat = cars 和 variable2 = vs 参数保持不变,但使用几个不同的列作为 variable1 参数.出于本示例的目的,假设它是以下 4 个变量:

What I really want, though, is to create lots of these tables where the dat = cars and variable2 = vs arguments stay the same, but using several different columns as the variable1 argument. For the purposes of this example, say it's the following 4 variables:

variables = c("cyl", "am", "gear", "carb")

我不确定 purrr 包中的 map 函数是否是执行此操作的最佳方法,但我一直未成功尝试使用 map 和 map_at 等相关函数进行各种不同的操作.如果有办法用 purrr 做到这一点,那么这就是我更愿意做的,但我愿意接受任何建议.我真的不在乎输出是什么样子,只是我可以得到我需要的所有交叉表,而无需多次复制和粘贴代码.

I'm not sure if a map function from the purrr package is the best way to do this, but I've been unsuccessfully trying all sorts of different things with map and related functions like map_at. If there is a way to do this with purrr then that's what I'd prefer to do, but I'm open to any suggestions. I don't really care what the output looks like, just that I can get all the crosstabs I need without copying and pasting code lots of times.

非常感谢任何帮助!

推荐答案

由于您的数据集和第二个变量是固定的,您可以像这样简化流程:

Since your dataset and second variable are fixed you can simplify the process like so:

library(tidyverse)
library(janitor)

imap(set_names(c("cyl", "am", "gear", "carb")), ~ mtcars %>%
       tabyl(!!rlang::sym(.x), vs, show_na = F) %>% 
       adorn_percentages("row") %>% 
       adorn_pct_formatting(digits = 1) %>% 
       adorn_ns() 
)

输出

$cyl
 cyl           0          1
   4   9.1%  (1) 90.9% (10)
   6  42.9%  (3) 57.1%  (4)
   8 100.0% (14)  0.0%  (0)

$am
 am          0         1
  0 63.2% (12) 36.8% (7)
  1 46.2%  (6) 53.8% (7)

$gear
 gear          0          1
    3 80.0% (12) 20.0%  (3)
    4 16.7%  (2) 83.3% (10)
    5 80.0%  (4) 20.0%  (1)

$carb
 carb          0          1
    1   0.0% (0) 100.0% (7)
    2  50.0% (5)  50.0% (5)
    3 100.0% (3)   0.0% (0)
    4  80.0% (8)  20.0% (2)
    6 100.0% (1)   0.0% (0)
    8 100.0% (1)   0.0% (0)


我使用 purrr::imappurrr::set_names(技术上来自 rlang 包)来保留输出中的变量名称列表.


I used purrr::imap and purrr::set_names (technically from the rlang package) to preserve the variable names in the output list.

这篇关于迭代 R 中交叉表的指定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆