tags:

views:

94

answers:

2

In a loop, I am trying to perform a simple renaming of the variables in a df.

Without the loop, this works perfectly:

names(c1) <- c("sales", "month")

With a loop-friendly approach ("1" in place of i in the dry-run example) the following correctly references names(c1):

names(get(paste("c","1", sep="")))

but as I write the whole operation I get an error to the tune of "only the first element is used as variable name", here's the code:

assign(names(get(paste("c","1", sep=""))), c("sales", "month"))

I don't know what the error means, but no column title has been changed.

Any ideas?

Thanks,

Roberto

A: 

assign takes a variable name as a string. get returns a variable, not its name.

In an attempt to taunt the R gods, here is a function that takes a string and a list of strings and assigns the list of strings to the name of the named data frame.

foo <- function(df, lon) {
  temp <- get(df)
  names(temp) <- lon
  assign(df, temp, inherits = TRUE)
}

There should be a way to do it without the copy.

deinst
*Shudder*. Why not just pass in the object itself? Working with names of objects is not a good strategy for success.
hadley
I agree. I'm just trying to answer the question as asked.
deinst
A: 

According to the assign function's help, the first argument is the variable's name, given as a character string. No coercion is done, and the first element of a character vector of length greater than one will be used, with a warning

gd047