3

我正在尝试编写一个相对简单的用户定义函数来输出交叉表,但不确定为什么它没有运行。

我的测试数据:

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 |
4

1 回答 1

2

参数weight_cat.w1weight_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)

}

于 2020-05-09T14:06:47.787 回答