3
y = 1

library(dplyr)

data.frame(x = 1, y = 2) %>%
  mutate(xy = x+y)

In the above example, xy will equal 3, but I want to use the global variable y to compute xy. How can I do that with dplyr?

xiaodai
  • 14,889
  • 18
  • 76
  • 140

1 Answers1

2

We can use (!!)

library(dplyr)
data.frame(x = 1, y = 2) %>%
     mutate(xy = x+ !!y)

-output

#  x y xy
#1 1 2  2

Or extract directly from the .GlobalEnv

data.frame(x = 1, y = 2) %>%
  mutate(xy = x+ .GlobalEnv$y)

-output

#  x y xy
#1 1 2  2
akrun
  • 874,273
  • 37
  • 540
  • 662