Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to use a global variable that clashes with column name a dplyr workflow?

Tags:

r

dplyr

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?

like image 790
xiaodai Avatar asked Dec 21 '25 20:12

xiaodai


1 Answers

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
like image 52
akrun Avatar answered Dec 23 '25 11:12

akrun