Jake Oliver Stephen
Jake Oliver Stephen

Reputation: 63

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.

Upvotes: 1

Views: 47

Answers (2)

MrFlick
MrFlick

Reputation: 206436

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.

Upvotes: 1

Hong Ooi
Hong Ooi

Reputation: 57696

Add the !! unquoting operator inside the is.na call:

finaldf <- df %>%
 mutate(!!storeddate := one+two) %>%
 filter(!is.na(!!storeddate))

Upvotes: 1

Related Questions