r - 在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 包会以某种方式使这变得复杂,否则我希望有一个非常简单的解决方案。
谢谢!
解决方案
你可以试试。
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
推荐阅读
- node.js - 如何使用 node.js 添加临时环境路径
- xcode - Fastlane 正在使用错误的帐户获取配置文件
- protractor - 如何在量角器中按跨度值定位元素?
- python - 交互式 VConcatChart 中的链接水平刻度?
- java - 加载 Apache Netbeans 9.0 或 10 时未找到 Java 错误
- html - ng-pick-datetimer 日历显示在对话框后面
- c - 为什么使用文本编辑器创建的文件比预期多一个字节?
- lua - Sublimetext3 使用 Lua 构建(Windows)
- mysql - 当特定数据发生变化时,从 MySQL 向 Jenkins 发出警报
- php - 如何在php mailer中设置发件人名称?