我有一个数据框,想要以两种方式之一过滤它,通过列"this"或列"that".我希望能够将列名称称为变量.如何(dplyr如果有所作为)我是否通过变量引用列名?
library(dplyr)
df <- data.frame(this = c(1, 2, 2), that = c(1, 1, 2))
df
# this that
# 1 1 1
# 2 2 1
# 3 2 2
df %>% filter(this == 1)
# this that
# 1 1 1
Run Code Online (Sandbox Code Playgroud)
但是说我想使用变量column来保存"this"或"that",并过滤任何值的值column.双方as.symbol并get在其他环境中工作,但不是这个:
column <- "this"
df %>% filter(as.symbol(column) == 1)
# [1] this that
# <0 rows> (or 0-length row.names)
df %>% filter(get(column) == 1)
# Error in get("this") …Run Code Online (Sandbox Code Playgroud) 我想写一个使用dplyr的函数,我提供变量名作为字符串.不幸的是,dplyr-s使用NSE使它变得相当复杂.从使用dplyr编程我得到以下示例
my_summarise <- function(df, var) {
var <- enquo(var)
df %>%
group_by(!!var) %>%
summarise(a = mean(a))
}
my_summarise(df, g1)
Run Code Online (Sandbox Code Playgroud)
但是,我想编写功能而不是g1我能提供的功能,"g1"而且我无法解决如何做到这一点.