3 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
對(duì)于dplyr版本[0.3-0.7)(?-2017年6月)
(有關(guān)最新dplyr版本,請(qǐng)參閱此問(wèn)題的其他答案)
從使用非標(biāo)準(zhǔn)評(píng)估(NSE,請(qǐng)參見(jiàn)發(fā)布和小插圖)的dplyr 0.3每個(gè)dplyr功能開(kāi)始, 標(biāo)準(zhǔn)評(píng)估(SE)雙胞胎以下劃線結(jié)尾。這些可用于傳遞變量。因?yàn)闀?huì)的。使用您可能會(huì)將邏輯條件作為字符串傳遞。filterfilter_filter_
filter_(df, "color=='blue'")
# color value
# 1 blue 1
# 2 blue 3
# 3 blue 4
用邏輯條件構(gòu)造字符串當(dāng)然很簡(jiǎn)單
l <- paste(var, "==", "'blue'")
filter_(df, l)

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超10個(gè)贊
在較新的版本中,我們可以使用我們可以創(chuàng)建帶引號(hào)的變量,然后取消引號(hào)(UQ或!!)以進(jìn)行評(píng)估
var <- quo(color)
filter(df, UQ(var) == "blue")
# color value
#1 blue 1
#2 blue 3
#3 blue 4
由于運(yùn)算符的優(yōu)先級(jí),我們可能需要()環(huán)繞!!
filter(df, (!!var) == "blue")
# color value
#1 blue 1
#2 blue 3
#3 blue 4
對(duì)于新版本,||優(yōu)先級(jí)更高,因此
filter(df, !! var == "blue")
應(yīng)該工作(如@Moody_Mudskipper評(píng)論)
較舊的選項(xiàng)
我們還可以使用:
filter(df, get(var, envir=as.environment(df))=="blue")
#color value
#1 blue 1
#2 blue 3
#3 blue 4
編輯:重新排列解決方案的順序

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
從dplyr 0.7開(kāi)始,某些情況再次發(fā)生了變化。
library(dplyr)
df <- data.frame(
color = c("blue", "black", "blue", "blue", "black"),
value = 1:5)
filter(df, color == "blue")
# it was already possible to use a variable for the value
val <- 'blue'
filter(df, color == val)
# As of dplyr 0.7, new functions were introduced to simplify the situation
col_name <- quo(color) # captures the current environment
df %>% filter((!!col_name) == val)
# Remember to use enquo within a function
filter_col <- function(df, col_name, val){
col_name <- enquo(col_name) # captures the environment in which the function was called
df %>% filter((!!col_name) == val)
}
filter_col(df, color, 'blue')
dplyr編程插圖中介紹了更多一般情況。
- 3 回答
- 0 關(guān)注
- 675 瀏覽
添加回答
舉報(bào)