Search code examples
rnon-standard-evaluation

R: Non-standard evaluation of dynamic variables within pipes. Replacing (") with (`)


I am attempting to use a dynamic string in a dplyr pipe and a lapply function. Where the string is used to name a column which is later used within a filter. The issue occurs where attempting filter to remove any rows with a resultant NA (using !is.na()) within the filter.

Typically one would use Non-standard evaluation such as filter_ for such a situation, however due to the called string being within is.na(), the filter_ has no effect. I require the string to be called wrapped using the prime symbol (`) as opposed to quotation marks (").

Below is a minimal example minus the lapply function.

df <- data.frame("one"=c(1,2,3,4),"two"=c(4,NA,2,1))
storeddate <- "Jan17-01-92"
finaldf <- df %>%
 mutate(!!storeddate := one+two) %>%
 filter(!is.na(storeddate)) #the storeddate string call requires formatting as `Jan17-01-92` as opposed to "Jan17-01-92".

I am aware that I could simply reformat the initial string, however I am more curious of finding a way to calls strings wrapped in a different format for use within other scenarios.


Solution

  • For the filter, you need to turn the string into a symbol. For example

    df %>%
      mutate(!!storeddate := one+two) %>% 
      filter(!is.na(!!as.name(storeddate)))
    
    #   one two Jan17-01-92
    # 1   1   4           5
    # 2   3   2           5
    # 3   4   1           5
    

    So it's not about replacing quotes. It the different between strings and symbols/names in R.