我正在尝试重命名 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/