这是一个可重现的例子
#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列信息。
答案 0 :(得分:3)
文档table_cols
表示您可以传递列名列表。所以这似乎做你想要的:
vars <- expression(list(vs, gear))
mtcars %>%
tab_cols(total(), eval(vars)) %>%
tab_cells(gear) %>%
tab_stat_cpct(total_row_position = "none", label = "col %") %>%
tab_pivot(stat_position = "inside_rows")
答案 1 :(得分:2)
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包的作者。