0

I am trying to use dplyr's new NSE language approach to create a conditional mutate, using a vector input. Where I am having trouble is setting the column equal to itself, see mwe below:

df <- data.frame("Name" = c(rep("A", 3), rep("B", 3), rep("C", 4)), 
                 "X" = runif(1:10), 
                 "Y" = runif(1:10)) %>% 
    tbl_df() %>% 
    mutate_if(is.factor, as.character)

ColToChange <- "Name"
ToChangeTo <- "Big"

Now, using the following:

df %>% mutate( !!ColToChange := ifelse(X >= 0.5 & Y >= 0.5, ToChangeTo, !!ColToChange))

Sets the ColToChange value to Name, not back to its original value. I am thus trying to use the syntax above to achieve this:

df %>% mutate( !!ColToChange := ifelse(X >= 0.5 & Y >= 0.5, ToChangeTo, Name))

But instead of Name, have it be the vector.

alistaire
  • 42,459
  • 4
  • 77
  • 117
Nick
  • 3,262
  • 30
  • 44
  • 2
    fwiw, this is trivial in base R: `df[df$X >= 0.5 & df$Y >= 0.5, ColToChange] <- ToChangeTo` – alistaire Jan 04 '18 at 19:12
  • @alistaire As with most questions on stack, the simplicity of the example belies the more intricate application... – Nick Jan 04 '18 at 20:35
  • It doesn't really matter; the complication only exists in dplyr because of its NSE, and thus _can't_ exist in base R. Writing dplyr for known variables (i.e. doing analysis) is much easier because of its NSE, but programming (i.e. writing packages) is usually easier in base R because of its SE. – alistaire Jan 04 '18 at 20:39

1 Answers1

5

You need to use rlang:sym to evaluate ColToChange as a symbol Name first, then evaluate it as a column with !!:

library(rlang); library(dplyr);

df %>% mutate(!!ColToChange := ifelse(X >= 0.5 & Y >= 0.5, ToChangeTo, !!sym(ColToChange)))

# A tibble: 10 x 3
#    Name          X         Y
#   <chr>      <dbl>     <dbl>
# 1     A 0.05593119 0.3586310
# 2     A 0.70024660 0.4258297
# 3   Big 0.95444388 0.7152358
# 4     B 0.45809482 0.5256475
# 5   Big 0.71348123 0.5114379
# 6     B 0.80382633 0.2665391
# 7   Big 0.99618062 0.5788778
# 8   Big 0.76520307 0.6558515
# 9     C 0.63928001 0.1972674
#10     C 0.29963517 0.5855646
Psidom
  • 209,562
  • 33
  • 339
  • 356