gpt4 book ai didi

r - 使用 expss::cro() 编写用户定义的函数

转载 作者:行者123 更新时间:2023-12-04 15:28:56 24 4
gpt4 key购买 nike

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

我的测试数据:

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 |

最佳答案

参数 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)

}

关于r - 使用 expss::cro() 编写用户定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61688170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com