Throw an error if not in dplyr tidyeval

I use dplyrand check the order. I am confused about how to check that someone put an object without an object against a string for NSE. For example, I would like to filter out missing data:


library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
df = data_frame(
  myvar = c(rep("yes", 2), NA)
)
myfun <- function(x){
  x = enquo(x)
  num = df %>%
    filter(!is.na( !! x)) 
  return(num)
}

myfun(myvar)
#> # A tibble: 2 x 1
#>   myvar
#>   <chr>
#> 1 yes  
#> 2 yes

I would like a string equivalent to error to be, if possible. This currently gives the “wrong” result, as it is is.na("myvar")never FALSE.

myfun("myvar") # wrong result
#> # A tibble: 3 x 1
#>   myvar
#>   <chr>
#> 1 yes  
#> 2 yes  
#> 3 <NA>

After viewing What is the tidyeval way of using dplyr :: filter? seems to filter_atallow both scripts to work fine:

myfun <- function(x){
  x = enquo(x)
  num = df %>%
    filter_at(vars( !! x), all_vars(!is.na(.)))
  return(num)
}

myfun(myvar)
#> # A tibble: 2 x 1
#>   myvar
#>   <chr>
#> 1 yes  
#> 2 yes
myfun("myvar") # correct result
#> # A tibble: 2 x 1
#>   myvar
#>   <chr>
#> 1 yes  
#> 2 yes

myfun("myvar") ? colnames(), , , , as.name.

+4
2

-

myfun <- function(x){
  x = enquo(x)
  stopifnot(!is.character(rlang::f_rhs(x)))
  num = df %>%
    filter(!is.na( !! x)) 
  return(num)
}

quosures , rlang::f_rhs "", , . , , .

myfun <- function(x){
  x = enquo(x)
  stopifnot(rlang::quo_is_symbol(x))
  num = df %>%
    filter(!is.na( !! x)) 
  return(num)
}

,

myfun(myvar) #works
myfun("myvar") #error
+3

x , . x , = 1, NA . () , length ( Error: object 'knockdown' not found), try(), .

myfun <- function(x){
try({if (length(x) == 1) return(NA)}, silent = TRUE)
x = enquo(x)
  num = df %>%
    filter_at(vars( !! x), all_vars(!is.na(.)))
  return(num)
}

myfun(myvar)
# A tibble: 2 x 1
  myvar
  <chr>
1 yes  
2 yes  

myfun("myvar")
[1] NA
0

Source: https://habr.com/ru/post/1695542/


All Articles