how to pass the strings with quotes as function arguments values

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'")

image

I do not know how to do what you want while passing a single string. In the following code I use three function arguments to allow filtering on a chosen column, using a chosen function and value. Is that close enough to what you need?

library(dplyr)
library(rlang)

adsl <- data.frame(SubjList=c(1:10), SAFFL=sample(c('Y','N'),10,replace = T))
adsl
#>    SubjList SAFFL
#> 1         1     N
#> 2         2     Y
#> 3         3     N
#> 4         4     N
#> 5         5     Y
#> 6         6     N
#> 7         7     Y
#> 8         8     N
#> 9         9     Y
#> 10       10     N
subs <- function(data=NA, VAR = SubjList, FUNC = `!=`,VAL = "" ) {
  data1 <- data |>  filter(FUNC({{VAR}},VAL))
  return(data1)
}

subs(data=adsl,SAFFL,`==`,'Y')
#>   SubjList SAFFL
#> 1        2     Y
#> 2        5     Y
#> 3        7     Y
#> 4        9     Y
subs(data=adsl,SubjList,`>`, 5)
#>   SubjList SAFFL
#> 1        6     N
#> 2        7     Y
#> 3        8     N
#> 4        9     Y
#> 5       10     N

Created on 2022-11-29 with reprex v2.0.2

try this

 data1 <- data %>% filter(eval(parse(text = subset)))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.