如何在循环中调用函数以计算R中的加权交叉表

问题描述

我想计算变量x与同一个y的几个dataframe变量之间的几个加权交叉表。我创建了一个函数来执行此操作,但是我无法循环y变量列表。

我给出了一个使用mpg数据的过程的示例:在这里,我的y变量是cylyearxclass

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,weights = mpg2$weight,: object 'mpg2' not found

# using a function
calc_table <- function(x,y) {
  return(questionr::wtd.table(x,y,na.show=FALSE))
}

# No problem when describing the variable as mpg2$cyl
calc_table(mpg2$class,mpg2$cyl)
#> Error in questionr::wtd.table(x,: 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,: object 'mpg2' not found

解决方法

问题是您使用mpg2[i]返回了数据帧或小标题,而不是mpg2[[i]]返回了向量。但是,除了这个问题,我建议循环遍历列名而不是位置。我还添加了一个列表来保存结果。试试这个:

library(dplyr)
library(questionr)

# include some weights in mpg2 (same weight)

mpg2 <- ggplot2::mpg %>%
  mutate(weight = 1/234)

# using a function
calc_table <- function(x,y) {
  questionr::wtd.table(x,y,weights=mpg2$weight,digits = 0,na.show=FALSE)
}

table_list <- list()
for (i in c("cyl","year")){
  print(table_list[[i]] <- calc_table(mpg2$class,mpg2[[i]]))
}
#>                      4           5           6           8
#> 2seater    0.000000000 0.000000000 0.000000000 0.021367521
#> compact    0.136752137 0.008547009 0.055555556 0.000000000
#> midsize    0.068376068 0.000000000 0.098290598 0.008547009
#> minivan    0.004273504 0.000000000 0.042735043 0.000000000
#> pickup     0.012820513 0.000000000 0.042735043 0.085470085
#> subcompact 0.089743590 0.008547009 0.029914530 0.021367521
#> suv        0.034188034 0.000000000 0.068376068 0.162393162
#>                   1999        2008
#> 2seater    0.008547009 0.012820513
#> compact    0.106837607 0.094017094
#> midsize    0.085470085 0.089743590
#> minivan    0.025641026 0.021367521
#> pickup     0.068376068 0.072649573
#> subcompact 0.081196581 0.068376068
#> suv        0.123931624 0.141025641