更改命名数据框的df列名称

时间:2011-12-12 18:05:49

标签: r

我正在尝试创建一个循环浏览某些数据框并将其列名更改为小写的脚本。

firmNames <- c("file1","file2","file3","file4","file5")
for(i in 1:length(firmNames)){
    fileName <- paste("data/",firmNames[i],".RData",sep="")
    load(fileName)
    upper <- names(get(firmNames[i]))
    lower <- tolower(upper)  # transforms to lower case
    names(get(firmNames[i])) <- lower  # This is the offending line
    save(get(firmNames[i]), file = fileName)
}

这会导致语法错误:

Error in names(get(firmNames[i])) <- lower : 
could not find function "get<-"

如果我使用assign,它仍会失败:

Error in save(get(firmNames[i]), file = fileName) : 
object ‘get(firmNames[i])’ not found
In addition: Warning message:
In assign(names(get(firmNames[i])), lower) :
only the first element is used as variable name

奇怪的是,打印names(get(firmNames[i]))完美显示,lower也是如此。它们都是模式特征。我错过了什么?

1 个答案:

答案 0 :(得分:2)

直观,可读且保持完整性的解决方案是将您要修改的data.frame分配给临时对象(此处命名为X)。对此进行处理,当您将其保持原状时,使用正确修改的对象覆盖原始对象:

# SETUP
firmNames <- c("file1","file2","file3","file4","file5")
file1 <- data.frame(ALLIGATOR=1:4, BLUEBIRD=rnorm(4))

file1
#   ALLIGATOR    BLUEBIRD
# 1         1 -0.37122263
# 2         2 -0.13939213
# 3         3 -0.79044157
# 4         4 -0.06837244


# MODIFY COLUMN NAMES
for (i in 1) {
    X <- get(firmNames[i])
    names(X) <- tolower(names(X))
    assign(firmNames[i], X)
}

file1
#   alligator    bluebird
# 1         1 -0.37122263
# 2         2 -0.13939213
# 3         3 -0.79044157
# 4         4 -0.06837244