旧行李 2011-09-23 16:08 采纳率: 25%
浏览 6560
已采纳

如何在 data.frame 中重命名单个列?

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

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]

转载于:https://stackoverflow.com/questions/7531868/how-to-rename-a-single-column-in-a-data-frame

  • 写回答

13条回答 默认 最新

  • lrony* 2011-09-23 17:01
    关注
    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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(12条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器