在dplyr函数中使用变量名

我想在中使用变量名作为字符串dplyr。请参阅以下示例:


df <- data.frame( 

      color = c("blue", "black", "blue", "blue", "black"), 

      value = 1:5)

filter(df, color == "blue")

它运行完美,但是我想color通过字符串来引用,就像这样:


var <- "color"

filter(df, this_probably_should_be_a_function(var) == "blue").

我很乐意以任何方式做到这一点,并且非常乐于使用易于阅读的dplyr语法。


慕勒3428872
浏览 447回答 3
3回答

守着一只汪

对于dplyr版本[0.3-0.7)(?-2017年6月)(有关最新dplyr版本,请参阅此问题的其他答案)从使用非标准评估(NSE,请参见发布和小插图)的dplyr 0.3每个dplyr功能开始, 标准评估(SE)双胞胎以下划线结尾。这些可用于传递变量。因为会的。使用您可能会将逻辑条件作为字符串传递。filterfilter_filter_filter_(df, "color=='blue'")#&nbsp; &nbsp;color value# 1&nbsp; blue&nbsp; &nbsp; &nbsp;1# 2&nbsp; blue&nbsp; &nbsp; &nbsp;3# 3&nbsp; blue&nbsp; &nbsp; &nbsp;4用逻辑条件构造字符串当然很简单l <- paste(var, "==",&nbsp; "'blue'")filter_(df, l)

LEATH

在较新的版本中,我们可以使用我们可以创建带引号的变量,然后取消引号(UQ或!!)以进行评估var <- quo(color)filter(df, UQ(var) == "blue")#&nbsp; &nbsp;color value#1&nbsp; blue&nbsp; &nbsp; &nbsp;1#2&nbsp; blue&nbsp; &nbsp; &nbsp;3#3&nbsp; blue&nbsp; &nbsp; &nbsp;4由于运算符的优先级,我们可能需要()环绕!!filter(df, (!!var) == "blue")#&nbsp; &nbsp;color value#1&nbsp; blue&nbsp; &nbsp; &nbsp;1#2&nbsp; blue&nbsp; &nbsp; &nbsp;3#3&nbsp; blue&nbsp; &nbsp; &nbsp;4对于新版本,||优先级更高,因此filter(df, !! var == "blue")应该工作(如@Moody_Mudskipper评论)较旧的选项我们还可以使用:&nbsp;filter(df, get(var, envir=as.environment(df))=="blue")&nbsp;#color value&nbsp;#1&nbsp; blue&nbsp; &nbsp; &nbsp;1&nbsp;#2&nbsp; blue&nbsp; &nbsp; &nbsp;3&nbsp;#3&nbsp; blue&nbsp; &nbsp; &nbsp;4编辑:重新排列解决方案的顺序

牛魔王的故事

从dplyr 0.7开始,某些情况再次发生了变化。library(dplyr)df <- data.frame(&nbsp;&nbsp; color = c("blue", "black", "blue", "blue", "black"),&nbsp;&nbsp; value = 1:5)filter(df, color == "blue")# it was already possible to use a variable for the valueval <- 'blue'filter(df, color == val)# As of dplyr 0.7, new functions were introduced to simplify the situationcol_name <- quo(color) # captures the current environmentdf %>% filter((!!col_name) == val)# Remember to use enquo within a functionfilter_col <- function(df, col_name, val){&nbsp; col_name <- enquo(col_name) # captures the environment in which the function was called&nbsp; df %>% filter((!!col_name) == val)}filter_col(df, color, 'blue')dplyr编程插图中介绍了更多一般情况。
打开App,查看更多内容
随时随地看视频慕课网APP