【发布时间】:2020-08-10 00:44:36
【问题描述】:
我有一个与 expss 表相关的(新)问题。我写了一个非常简单的UDF(依赖几个expss函数),如下:
library(expss)
z_indices <- function(x, m_global, std_global, weight=NULL){
if(is.null(weight)) weight = rep(1, length(x))
z <- (w_mean(x, weight)-m_global)/std_global
indices <- 100+(z*100)
return(indices)
}
可重现的示例,基于infert 数据集(加上任意权重的向量):
data(infert)
infert$w <- as.vector(x=rep(2, times=nrow(infert)), mode='numeric')
infert %>%
tab_cells(age, parity) %>%
tab_cols(total(), education, case %nest% list(total(), education)) %>%
tab_weight(w) %>%
tab_stat_valid_n(label="N") %>%
tab_stat_mean(label="Mean") %>%
tab_stat_fun(label="Z", function(x, m_global, std_global, weight=NULL){
z_indices(x, m_global=w_mean(infert$age, infert$w),std_global=w_sd(infert$age, infert$w))
}) %>%
tab_pivot(stat_position="inside_columns")
计算表格并且第一行的输出(几乎)符合预期。
然后第二行的事情变得一团糟,因为z_indices 的两个参数都明确引用infert$age,其中infert$parity 是预期的。
我的问题:有没有办法将tab_cells 的变量作为函数参数动态传递给tab_stat_fun 以匹配正在处理的变量?我猜这发生在函数声明中,但不知道如何继续......
谢谢!
2020 年 4 月 28 日编辑: @Gregory Demin 的回答在推断数据集的范围内效果很好,尽管为了更好地扩展更大的数据帧,我编写了以下循环:
var_df <- data.frame("age"=infert$age, "parity"=infert$parity)
tabZ=infert
for(each in names(var_df)){
tabZ = tabZ %>%
tab_cells(var_df[each]) %>%
tab_cols(total(), education) %>%
tab_weight(w) %>%
tab_stat_valid_n(label="N") %>%
tab_stat_mean(label="Mean") %>%
tab_stat_fun(label="Z", function(x, m_global, std_global, weight=NULL){
z_indices(x, m_global=w_mean(var_df[each], infert$w),std_global=w_sd(var_df[each], infert$w))
})
}
tabZ = tabZ %>% tab_pivot()
希望这对未来的其他 expss 用户有所启发!
【问题讨论】:
标签: r user-defined-functions weighted expss