r - colnames 命令产生错误 : attribute [13] must be the same length as the vector [12]

标签 r

我正在尝试重命名 data.frame 中的列。但是,当我尝试在 R 中运行 names 或 colnames 命令时,我不断收到以下错误

Error in names(HourlyTotal)["ZoneElectric"] <- "Meas.Elec" : 
  'names' attribute [13] must be the same length as the vector [12]

这是我要运行的代码:

names(HourlyTotal)["ZoneElectric"] <- "Meas.Elec"

但是,如果我使用列号而不是列名,代码可以正常工作。

names(HourlyTotal)[3] <- "Meas.Elec"

知道为什么会发生这种情况吗?感谢您的帮助,因为这让我困惑了一段时间。

最佳答案

当您编写 names(HourlyTotal)["ZoneElectric"] 时,您要求 R 为您提供名为 "ZoneElectric" 的元素来自向量 names(HourlyTotal)

但是,names(HourlyTotal) 是一个未命名的向量。

您想要的(我猜测/假设)是 names(HourlyTotal) 的元素,其 value"ZoneElectric “。如果您碰巧知道它出现在向量中的哪个位置,那么您可以使用数字索引,正如您所发现的那样(即 names(HourlyTotal)[3])。但是,更可靠的解决方案是针对该特定值进行过滤:

因此,使用:

names(HourlyTotal)[names(HourlyTotal) == "ZoneElectric"] <- ... 

# Instead of 
#    names(HourlyTotal)["ZoneElectric"] <- ... 

或者您可以使用 data.table 包中的 setnames:

library(data.table)
setnames(HourlyTotal, old="ZoneElectric", new="NewName")

关于r - colnames 命令产生错误 : attribute [13] must be the same length as the vector [12],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19527339/

相关文章:

Linux安装问题-R

r - 集成错误 : maximum number of subdivisions reached

r - 如何从 kable() 为表中的名称添加下标?

r - 如何防止在 R 中调整字体、绘图对象等的大小?

r - 有没有办法在 ggplot2 中手动设置水平箱线图的高度? (垂直闪避)

r - 将字符转换为数字而不丢失 R 中的小数

r - 将函数应用于 R 中嵌套列表的某些元素

r - 在 R 中按年份计算偏斜和峰度

r - 任何/所有的有效版本

r - 作业 : Simulating coin tosses until consecutive heads using R