r - 使用字符串变量在 R 函数内部传递多个变量信息

标签 r lazy-evaluation expss

这是一个可重现的例子

#install.packages("expss")
library("expss")
data(mtcars)
mtcars = apply_labels(mtcars,
                      mpg = "Miles/(US) gallon",
                      cyl = "Number of cylinders",
                      disp = "Displacement (cu.in.)",
                      hp = "Gross horsepower",
                      drat = "Rear axle ratio",
                      wt = "Weight (1000 lbs)",
                      qsec = "1/4 mile time",
                      vs = "Engine",
                      vs = c("V-engine" = 0,
                             "Straight engine" = 1),
                      am = "Transmission",
                      am = c("Automatic" = 0,
                             "Manual"=1),
                      gear = "Number of forward gears",
                      carb = "Number of carburetors"
)

mtcars %>%
  tab_cols(total(),vs,gear) %>%
  tab_cells(gear) %>% 
  tab_stat_cpct(total_row_position = "none", label = "col %") %>%
  tab_pivot(stat_position = "inside_rows") 

根据我的情况,我想动态传递 tab_cols(total(),vs,gear) 中的变量信息。因此,为了便于使用,假设我想评估如下函数:
var1 <- "vs, gear"

mtcars %>%
  tab_cols(total(),var1) %>%
  tab_cells(gear) %>% 
  tab_stat_cpct(total_row_position = "none", label = "col %") %>%
  tab_pivot(stat_position = "inside_rows") 

显然,这给出了错误!我知道仅适用于单个参数的惰性求值。因此尝试了很多在多个论坛上搜索但没有运气。

所以,一种很好的方法可能是:
var1 <- "vs"
var2 <- "gear"
mtcars %>%
  tab_cols(total(),eval(parse(text = var1)),eval(parse(text = var2))) %>%
  tab_cells(gear) %>% 
  tab_stat_cpct(total_row_position = "none", label = "col %") %>%
  tab_pivot(stat_position = "inside_rows") 

但我想用单个变量(它将具有字符串或向量形式的变量信息)来实现这一点,因为该变量可能存储超过 3 或 4 列信息。

最佳答案

在 expss 中有一个特殊的工具来传递参数:

var1 <- "vs, gear"
var_names = trimws(unlist(strsplit(var1, split = ","))) 

mtcars %>%
    tab_cols(total(), ..[(var_names)]) %>%
    tab_cells(gear) %>% 
    tab_stat_cpct(total_row_position = "none", label = "col %") %>%
    tab_pivot(stat_position = "inside_rows") 

免责声明:我是 expss 包的作者。

关于r - 使用字符串变量在 R 函数内部传递多个变量信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49879724/

相关文章:

r - 将堆叠矩阵转换为分块矩阵

R 代码运行时间太长

r - 使用 R expss 和 data.table 是否可以从 csv 文件加载 data.table 标签,而不是手动输入代码?

r - R 中的条件交叉表

r - 匹配不同长度的时间向量 : a tricky one

r - 汇总一个向量,然后将汇总统计信息附加到 R 中的原始数据帧

.net - Lazy<T> 和线程安全 false 的含义

r - 如何在ggplot中使用带有准引号的cut_width?

haskell - 是否有更严格的Data.Sequence?

r - R 中具有多个条件的 count_if (EXPSS)