开发者

Iterating over column names in a data frame

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜