我知道如果我有一个包含多于一列的数据帧,那么我可以使用

colnames(x) <- c("col1","col2")

重命名列。如果只有一列,该怎么做呢? 意思是只有一列的向量或数据帧。

例子:

trSamp <- data.frame(sample(trainer$index, 10000))
head(trSamp )
#   sample.trainer.index..10000.
# 1                      5907862
# 2                      2181266
# 3                      7368504
# 4                      1949790
# 5                      3475174
# 6                      6062879

ncol(trSamp)
# [1] 1
class(trSamp)
# [1] "data.frame"
class(trSamp[1])
# [1] "data.frame"
class(trSamp[,1])
# [1] "numeric"
colnames(trSamp)[2] <- "newname2"
# Error in names(x) <- value : 
#   'names' attribute [2] must be the same length as the vector [1]

当前回答

我认为重命名列的最好方法是像这样使用dplyr包:

require(dplyr)
df = rename(df, new_col01 = old_col01, new_col02 = old_col02, ...)

对于重命名任何数据集中的一个或多个列,它的工作原理相同。

其他回答

Try:

colnames(x)[2] <- 'newname2'
colnames(trSamp)[2] <- "newname2"

尝试设置第二列的名称。对象只有一列,因此该命令会抛出错误。这就足够了:

colnames(trSamp) <- "newname2"

OP的问题已经得到了很好的回答。然而,这里有一个在某些情况下可能有用的技巧:部分匹配列名,不管它在数据框架中的位置:

名称部分匹配:

d <- data.frame(name1 = NA, Reported.Cases..WHO..2011. = NA, name3 = NA)
##   name1 Reported.Cases..WHO..2011. name3
## 1    NA                         NA    NA
names(d)[grepl("Reported", names(d))] <- "name2"
##   name1 name2 name3
## 1    NA    NA    NA

另一个例子:标点符号出现时的部分匹配:

d <- data.frame(name1 = NA, Reported.Cases..WHO..2011. = NA, name3 = NA)
##   name1 Reported.Cases..WHO..2011. name3
## 1    NA                         NA    NA
names(d)[grepl("[[:punct:]]", names(d))] <- "name2"
##   name1 name2 name3
## 1    NA    NA    NA

这些都是我今天要处理的例子,我认为可能值得分享。

如果你知道你的数据帧只有一列,你可以使用: names(trSamp) <- "newname2"

我将简单地用下面的代码用我想要的新名称更改数据集的列名: name (dataset)[index_value] <- "new_col_name"