我知道如果我有一个包含多于一列的数据帧,那么我可以使用
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::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
适用于管道链
当名称存储在变量中时很方便
与名称或列索引一起使用
清晰紧凑
我发现colnames()参数更容易
https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/row%2Bcolnames
从数据帧中选择某一列
df <- data.frame(df[, c( "hhid","b1005", "b1012_imp", "b3004a")])
并按顺序重命名所选列,
colnames(df) <- c("hhid", "income", "cost", "credit")
检查名称和值以确定
names(df);head(df)
我发现重命名单个列最方便的方法是使用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
适用于管道链
当名称存储在变量中时很方便
与名称或列索引一起使用
清晰紧凑
这是一个老问题,但值得注意的是,您现在可以从数据中使用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)