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.)
An option is to check for the object in the global environment instead of the local environment
library(dplyr)
df %>%
mutate(z = .GlobalEnv$z)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With