我试图编写一个相对简单的用户定义函数来输出跨表,但不太确定为什么它没有运行。
我的测试数据:
fp_within = structure(list(weight_cat.w1 = structure(c(1L, 2L, 2L, 1L, 1L,
2L, 1L, 1L, 3L, 3L, 3L, 3L, NA, 3L, 3L, 2L, NA, NA, NA, NA), .Label = c("1",
"2", "3"), label = "Weight (Wave 1)", class = c("labelled", "factor"
)), weight_cat.w2 = structure(c(1L, 2L, 2L, 1L, 1L, 2L, 1L, NA,
2L, 3L, 3L, 2L, 1L, 3L, 3L, 2L, 2L, 2L, 3L, 1L), .Label = c("1",
"2", "3"), label = "Weight (Wave 2)", class = c("labelled", "factor"
))), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"
))我的代码:
library(expss)
library(tidyr)
xtable = function(wave1, wave2, name) {
xtab = fp_within %>%
tab_cells(wave1) %>%
tab_cols(wave2) %>%
tab_stat_cases() %>% # tab_stat_cases = counts
tab_pivot() %>%
set_caption(glue("Table showing agreement in {name} across waves (N)"))
return(xtab)
}
xtable(weight_cat.w1, weight_cat.w2, "weight")这会抛出一个错误,上面写着..。
Error in eval(expr, envir = e, enclos = baseenv()) :
object 'weight_cat.w1' not found这在函数之外工作,我期望输出如下所示:
Table showing agreement in weight across waves (N)
| | | Weight (Wave 2) | | |
| | | 1 | 2 | 3 |
| --------------- | ------------ | --------------- | ---- | ---- |
| Weight (Wave 1) | 1 | 1519 | 309 | 5 |
| | 2 | 300 | 1229 | 299 |
| | 3 | 6 | 278 | 1559 |
| | #Total cases | 1825 | 1816 | 1863 |发布于 2020-05-09 14:06:47
参数weight_cat.w1和weight_cat.w2是在讨论tab_*之前进行计算的。因为在您的数据集之外没有这样的变量,所以引发错误。为了避免初步评估,您需要通过使用eval(substitute(...))来特别注意它
xtable = function(wave1, wave2, name) {
xtab = eval(substitute({
fp_within %>%
tab_cells(wave1) %>%
tab_cols(wave2) %>%
tab_stat_cases() %>% # tab_stat_cases = counts
tab_pivot()%>%
set_caption(glue("Table showing agreement in {name} across waves (N)"))
}))
return(xtab)
}https://stackoverflow.com/questions/61688170
复制相似问题