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

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, ...)

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

其他回答

library(dplyr)
rename(data, de=de.y)

Try:

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

您可以使用重命名。gdata包中的Vars。

library(gdata)
df <- rename.vars(df, from = "oldname", to = "newname")

当你有多个变量名要修改,或者你想在变量名后面追加或预先添加一些文本时,这是特别有用的,你可以这样做:

df <- rename.vars(df, from = c("old1", "old2", "old3", 
         to = c("new1", "new2", "new3"))

有关将文本附加到变量名称子集的示例,请参阅: https://stackoverflow.com/a/28870000/180892

我发现重命名单个列最方便的方法是使用dplyr::rename_at:

library(dplyr)
cars %>% rename_at("speed",~"new") %>% head     
cars %>% rename_at(vars(speed),~"new") %>% head
cars %>% rename_at(1,~"new") %>% head

#   new dist
# 1   4    2
# 2   4   10
# 3   7    4
# 4   7   22
# 5   8   16
# 6   9   10

适用于管道链 当名称存储在变量中时很方便 与名称或列索引一起使用 清晰紧凑

让df是你拥有的数据框架,col名称为myDays和temp。 如果你想把"myDays"重命名为"Date"

library(plyr)
rename(df,c("myDays" = "Date"))

或者用管子,你可以

dfNew      <- df %>% 
  plyr::rename(c("myDays" = "Date"))