我有一个数据框,想要以两种方式之一过滤它,通过列"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) 我不知道为什么从自定义函数传递参数不起作用group_by。我只是传递colName来自数据集的数据,当我运行自己的函数时,会出现错误:必须按 .data 中找到的变量进行分组。未找到列“colName”。在下面的示例中,我使用quakesR 环境中可用的数据集:
foo <- function(data, colName) {
result <- data %>%
group_by(colName) %>%
summarise(count = n())
return(result)
}
foo(quakes, "stations")
# I also tried passing w/o commas but it is not working too:
# foo(quakes, stations)
Run Code Online (Sandbox Code Playgroud)
我注意到,当我显式传递列名称时,group_by它会起作用:
group_by(stations) %>%
Run Code Online (Sandbox Code Playgroud)
但是,在函数中对列名称进行硬编码是没有意义的。
我想定义一个函数,该函数接受一个data.frame和一个列名,并以转换后的列(例如,转换为小写)的形式返回data.frame。如果事先知道列名,则很简单:
diamonds %>% mutate(cut = tolower(cut))
Run Code Online (Sandbox Code Playgroud)
我如何定义一个函数foo,例如:
col <- "cut"
foo(diamonds, col)
Run Code Online (Sandbox Code Playgroud)
是否有同样的行为?(data.table因为我想保留dplyr的能力,而不是寻找基本的R或答案,所以我希望保留将其转换为延迟评估的SQL调用的能力)。
如果我只是想使用以下功能来工作:foo(diamonds, cut),我只需要enquo和!!
foo <- function(df, col){
x <- enquo(col)
mutate(df, !!x := tolower(!!x))
}
Run Code Online (Sandbox Code Playgroud)
如果我想将列名用引号引起来 foo(diamonds, "cut"),则添加ensym就足够了:
foo <- function(df, col){
col <- ensym(col)
x <- enquo(col)
mutate(df, !!x := tolower(!!x))
}
Run Code Online (Sandbox Code Playgroud)
但这在为变量提供变量时失败:
col <- "cut"
foo(diamonds, col)
Error in ~col : object 'col' not found
Run Code Online (Sandbox Code Playgroud)
我缺少什么可以评估变量的信息?
我一直在阅读这篇关于如何使用 dplyr 中变量的字符串引用的文章。
我想根据字符串输入改变现有列:
var <- 'vs'
my_mtcars <- mtcars %>%
mutate(get(var) = factor(get(var)))
Run Code Online (Sandbox Code Playgroud)
错误:意外的“=”:“my_mtcars <- mtcars %>% mutate(get(var) ="
还尝试过:
my_mtcars <- mtcars %>%
mutate(!! rlang::sym(var) = factor(!! rlang::symget(var)))
Run Code Online (Sandbox Code Playgroud)
这导致了完全相同的错误消息。
如何根据在 var 变量中传递字符串“vs”进行变异来执行以下操作?
# works
my_mtcars <- mtcars %>%
mutate(vs = factor(vs))
Run Code Online (Sandbox Code Playgroud) 我希望能够filter(),其中参数值是已经定义的变量。
因此,例如,使用可重现的mtcars数据集:
library(tidyverse)
df <- mtcars
head(df)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
#> Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
#> Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 …Run Code Online (Sandbox Code Playgroud)