Fabian Gehring
Fabian Gehring

Reputation: 1173

R, dpylr handling variablenames that are identical to column names

When using dplyr and variablenames which are identical to column names, how do I distinguish between the two?

test <- c(1,2)
df <- data.frame(test = c(3,4))
df %>% mutate(test = test) # does not change anything

I also tried something like

test <- c(1,2)
df <- data.frame(test = c(3,4))
df %>% mutate(test = interp(~x, x = as.name("test")))

To force the use of the (global) variable "test" instead, unfortunately no success.

How do I handle such situations?

Edit: When having non non-global vars, i.e. function arguments

foo <- function(test) {
  df <- data.frame(test = c(3,4))
  env <- environment()
  df %>% mutate(test = env[["test"]])
}
foo(1:2)

Does the trick

Upvotes: 1

Views: 49

Answers (1)

akrun
akrun

Reputation: 887541

We can use .GlobalEnv to extract the objects

df %>% 
    mutate(test = .GlobalEnv[["test"]])
#    test
#1    1
#2    2

Upvotes: 1

Related Questions