我正在使用mtcars数据集来说明我的问题.
例如,我想将数据子集到4缸汽车.我可以这样做:
mtcars %>% filter(cyl == 4)
Run Code Online (Sandbox Code Playgroud)
在我的工作中,我需要传递一个字符串变量作为我的列名.例如:
var <- 'cyl'
mtcars %>% filter(var == 4)
Run Code Online (Sandbox Code Playgroud)
我也做了:
mtcars %>% filter(!!var == 4)
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,我都得到了空数据帧.
我有一个数据框,想要以两种方式之一过滤它,通过列"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)