1

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.

2 Answers2

1

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

finaldf <- df %>%
 mutate(!!storeddate := one+two) %>%
 filter(!is.na(!!storeddate))
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
  • Did you test this? What version of dplyr are you using? This did not work for me. It did not filter out the row with the NA. – MrFlick Apr 19 '18 at 19:29
1

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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Great, the unquoting as `as.name` does the trick! Thanks for the tip about strings, symbols and names. I wasn't sure on the terminology. (I have upvoted this answer, but too low a reputation!) – Jake Oliver Stephen Apr 19 '18 at 20:06