首页 > 解决方案 > 在R中的列表中访问tbl中的变量

问题描述

我试图弄清楚如何编写一个函数来访问存储在列表中的 tbl 中的变量。我正在使用 srvyr 包,因为我还需要合并调查设计元素。

#Example

library(tidyverse)
library(srvyr)

num <- c(1:50)
var <- rnorm(50)

data <- data.frame(num, var) %>%
  mutate(name = ifelse(num > 25, "Yes", "No"))

#This works fine as long as it's a dataframe

foo <- function(x)  {
  data %>%
    group_by(data[,x]) %>%
    summarise(n = n())
}

foo("name")

#With a slight edit this works for a tbl.

data_tbl <- as.tbl(data)

foo2 <- function(x)  {
  data_tbl %>%
    group_by(data_tbl[[x]]) %>%
    summarise(n = n())
}

foo2("name")

#Now the question is how to make this work for a tbl in a list.

sur <- data %>%
  as_survey_design(ids = 1)

#This seems to access what I want.

sur$variables[["name"]]

#But it doesn't work inside the function. 

foo3 <- function(x)  {
  sur %>%
    group_by(sur$variables[[x]]) %>%
    summarise(proportion = survey_mean())
}

foo3("name")

#Any thoughts?

有任何想法吗?除非使用 srvyr 包会以某种方式使这变得复杂,否则我希望有一个非常简单的解决方案。

谢谢!

标签: r

解决方案


你可以试试。

foo3 <- function(x)  {
  sur %>%
    group_by_at(x) %>% 
    summarise(proportion = survey_mean())
}

foo3("name")

输出

# A tibble: 2 x 3
  name  proportion proportion_se
  <chr>      <dbl>         <dbl>
1 No           0.5        0.0714
2 Yes          0.5        0.0714

推荐阅读