我知道如果我有一个包含多于一列的数据帧,那么我可以使用
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]
这也可以使用Hadley的plyr包和rename函数来完成。
library(plyr)
df <- data.frame(foo=rnorm(1000))
df <- rename(df,c('foo'='samples'))
您可以根据名称重命名(不知道位置),并一次执行多个重命名。例如,在进行合并之后,你可能会得到:
letterid id.x id.y
1 70 2 1
2 116 6 5
3 116 6 4
4 116 6 3
5 766 14 9
6 766 14 13
然后你可以在一个步骤重命名使用:
letters <- rename(letters,c("id.x" = "source", "id.y" = "target"))
letterid source target
1 70 2 1
2 116 6 5
3 116 6 4
4 116 6 3
5 766 14 9
6 766 14 13
这是一个老问题,但值得注意的是,您现在可以从数据中使用setname。表方案。
library(data.table)
setnames(DF, "oldName", "newName")
# or since the data.frame in question is just one column:
setnames(DF, "newName")
# And for reference's sake, in general (more than once column)
nms <- c("col1.name", "col2.name", etc...)
setnames(DF, nms)
您可以使用重命名。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