如何重命名 data.frame 中的单个列? [英] How to rename a single column in a data.frame?

查看:45
本文介绍了如何重命名 data.frame 中的单个列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如果我有一个多于 1 列的数据框,我可以使用

I know if I have a data frame with more than 1 column, I can use

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

重命名列.如果它只是一列,我该怎么做?表示只有一列的向量或数据框.

to rename the columns. How do I do this if it's just one column? Meaning a vector or data frame with only one column in it.

示例:

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]

推荐答案

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

尝试设置第二列的名称.您的对象只有一列,因此该命令会引发错误.这应该足够了:

attempts to set the second column's name. Your object only has one column, so the command throws an error. This should be sufficient:

colnames(trSamp) <- "newname2"

这篇关于如何重命名 data.frame 中的单个列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆