2017-07-08 39 views
3

我有一些愚蠢的問題,使用懶惰評估和dplyr。 我試圖過濾一些NA s,不知道爲什麼lazyeval版本不起作用。可能我錯過了一些東西,但我找不到它。是這樣或者是一個錯誤?懶惰eval,dplyr「過濾器」和NAs

這裏是一個最小重複的例子:

library(dplyr) 
library(lazyeval) 

data(iris) 
iris$t <- c(1:140, rep(NA, 10)) 

#This Works 
temp <- filter(iris, !is.na(t)) 

#This doesn't 
temp <- filter_(iris, interp(~(!is.na(x)), x="t")) 

兩個碼運行不引發出一個錯誤。

+0

什麼dplyr的版本? –

+0

不太舊,0.5.0。安裝最新版本並嘗試。 – Elijah

回答

2

您需要通過"t"作爲名稱。

interp(~(!is.na(x)), x = as.name("t")) 
# ~!is.na(t) 

當你的代碼表示,要插入到"t"is.na()使is.na("t"),每次哪個是假的。否定每次都會給出TRUE,因此所有的行都是這樣。

interp(~(!is.na(x)), x = "t") 
# ~!is.na("t") 
+0

謝謝!我知道我忘記了一些東西! – Elijah

2

dplyr已切換從lazyeval其NSE系統rlang(記錄here),有利於新的語法棄用*_功能:

library(dplyr) 

data(iris) 
iris <- iris %>% mutate(t = c(1, rep(NA, 149))) 

# normal NSE 
iris %>% filter(!is.na(t)) 
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species t 
#> 1   5.1   3.5   1.4   0.2 setosa 1 

# string-based SE; use `rlang::sym` to convert to quosure and !! to unquote 
x <- "t" 
iris %>% filter(!is.na(!!rlang::sym(x))) 
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species t 
#> 1   5.1   3.5   1.4   0.2 setosa 1 

# program your own NSE with `quo` and friends 
x <- quo(t) 
iris %>% filter(!is.na(!!x)) 
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species t 
#> 1   5.1   3.5   1.4   0.2 setosa 1 

# both versions work across the tidyverse 
iris %>% tidyr::drop_na(!!x) 
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species t 
#> 1   5.1   3.5   1.4   0.2 setosa 1 

# though tidyr::drop_na is happy with strings anyway 
iris %>% tidyr::drop_na("t") 
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species t 
#> 1   5.1   3.5   1.4   0.2 setosa 1