Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variable shadowed by column in dplyr mutate [duplicate]

Tags:

r

dplyr

tidyverse

Given a data frame df and a local variable z, I'd like to set the column y of df to be equal to z:

df <- data.frame(x=1:5)
z <- 5
df %>%
  mutate(y = z)

However, if a column named z already exists in df, this sets y equal to that column instead of equal to the value of the local variable:

df <- data.frame(x=1:5, z=4)
z <- 5
df %>%
  mutate(y = z)

How do I ensure that I'm setting it to the local variable instead, regardless of the columns present in df?

(I understand that I could rename/drop the offending columns, but I'm dealing with data whose columns are not known ahead of runtime.)

like image 875
Corey Staten Avatar asked Sep 10 '19 17:09

Corey Staten


1 Answers

An option is to check for the object in the global environment instead of the local environment

library(dplyr)
df %>% 
   mutate(z = .GlobalEnv$z)
like image 163
akrun Avatar answered Oct 20 '22 04:10

akrun