[R] Variable names conflict

Axel Urbiz axel.urbiz at gmail.com
Thu Oct 15 18:42:42 CEST 2015


Hello,

I have a variable named 'x' defined inside a function, which   may conflict
with a variable name supplied in the argument to the function. What is the
best practice to avoid this conflict?

foo <- function(df) {
  x <- df[, 1, drop = FALSE]
  dfOut <- data.frame(df, x)
  dfOut

}
Data <- data.frame(x = c(1, 2), y = c(3, 4))
foo(Data)

  x y x.1
1 1 3   1
2 2 4   2

The following solution doesn't look nice to me…

foo <- function(df) {
  if (any(names(df) == 'x'))
    stop("x cannot be a variable name in the data frame")
  x <- df[, 1, drop = FALSE]
  dfOut <- data.frame(df, x)
  dfOut

}

Thanks!
Axel.

	[[alternative HTML version deleted]]



More information about the R-help mailing list