【发布时间】:2020-09-30 14:47:51
【问题描述】:
我想计算变量x 和同一dataframe 的几个y 变量之间的几个加权交叉表。我创建了一个函数来执行此操作,但我无法循环我的 y 变量列表。
我给出了一个使用mpg 数据的过程示例:这里,我的y 变量是cyl 和year。 x 是 class。
library(questionr)
# include some weights in mpg2 (same weight)
mpg2 <- mpg %>%
mutate(weight = 1/234)
#> Error in mpg %>% mutate(weight = 1/234): could not find function "%>%"
# crosstab class by cyl using weights
questionr::wtd.table(mpg2$class, mpg2$cyl,
weights=mpg2$weight,
digits = 0, na.show=FALSE)
#> Error in questionr::wtd.table(mpg2$class, mpg2$cyl, weights = mpg2$weight, : object 'mpg2' not found
# using a function
calc_table <- function(x, y) {
return(questionr::wtd.table(x, y,
weights=mpg2$weight,
digits = 0, na.show=FALSE))
}
# No problem when describing the variable as mpg2$cyl
calc_table(mpg2$class, mpg2$cyl)
#> Error in questionr::wtd.table(x, y, weights = mpg2$weight, digits = 0, : object 'mpg2' not found
# But I want to crosstab class with cyl (mpg2[5])
# and also class with year (mpg2[4])
# referencing the variable in a loop
# My main goal is to use the function for several variables
for (i in c(4:5)){
calc_table(mpg2$class, mpg2[i])
}
#> Error in questionr::wtd.table(x, y, weights = mpg2$weight, digits = 0, : object 'mpg2' not found
【问题讨论】: