My strategy is to be specific about the names of columns at the top level. As I
see it, letting functions internally come up with their own column names makes
fragile code.
foo <- function(df, newColName ) {
x <- setNames( df[, 1, drop = FALSE], newColName )
dfOut <- data.frame(df, x)
dfOut
}
Axel,
The solution you propose looks fine to me, if an error is the outcome that
you want in such a situation. Were you hoping for a different outcome?
Would you, for example, prefer that the "x" in the data frame be given a
different name, rather than the "x" in the function?
Jean
On Thu, Oct
May this be fine ?
foo <- function(df) {
x <- df[, 1, drop = FALSE]
available <- rev(letters[(letters %in% colnames(df)) == FALSE])
colnames(x) <- available[1]
dfOut <- data.frame(df, x)
dfOut
}
Data <- data.frame(x = c(1, 2), y = c(3, 4))
foo(Data)
x y z
1 1 3 1
2 2 4 2
--
GG
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 <- da
4 matches
Mail list logo