I am facing issue as below where I am unable to use the string with quotes as a function argument value, here is program where i am creating a simple function to subset the data based on the string subset condition as below. I am using the rlang package curly curls {{ but this seems not working any thoughts
adsl <- data.frame(SubjList=c(1:10), SAFFL=sample(c('Y','N'),10,replace = T))
subs <- function(data=NA,subset='SubjList!=""'){
data1 <- data %>% filter({{subset}})
return(data1)
}
subs(data=adsl,subset = "SAFFL=='Y'")
CodePudding user response:
Edit
One solution is to use the parse_expr()
function from the rlang package (https://rlang.r-lib.org/reference/parse_expr.html) and the bang-bang operator:
library(tidyverse)
library(rlang)
adsl <- data.frame(SubjList=c(1:10),
SAFFL=sample(c('Y','N'),10,
replace = T))
subs <- function(data, subset) {
data1 <- data %>% filter(!!parse_expr((subset)))
return(data1)
}
subs(data = adsl, subset = 'SAFFL == "Y"')
#> SubjList SAFFL
#> 1 1 Y
#> 2 3 Y
#> 3 4 Y
#> 4 5 Y
#> 5 6 Y
#> 6 7 Y
#> 7 10 Y
Created on 2022-11-30 with reprex v2.0.2
Original answer
One potential solution is to specify the variable (i.e. "SAFFL") and the value ("Y" or "N") separately, e.g.
library(tidyverse)
adsl <- data.frame(SubjList=c(1:10),
SAFFL=sample(c('Y','N'),10,
replace = T))
subs <- function(data, var, value){
data1 <- data %>% filter(.data[[var]] == value)
return(data1)
}
subs(data = adsl, var = "SAFFL", value = "Y")
#> SubjList SAFFL
#> 1 4 Y
#> 2 5 Y
subs(data = adsl, var = "SAFFL", value = "N")
#> SubjList SAFFL
#> 1 1 N
#> 2 2 N
#> 3 3 N
#> 4 6 N
#> 5 7 N
#> 6 8 N
#> 7 9 N
#> 8 10 N
Created on 2022-11-30 with reprex v2.0.2
Does that work for your use-case? Or do you need to pass the variable and the value together for some reason?