在R中遇到错误。
Error in names(x) <- value :
'names' attribute must be the same length as the vector
这个错误是什么意思?
在R中遇到错误。
Error in names(x) <- value :
'names' attribute must be the same length as the vector
这个错误是什么意思?
按照 @Chris W 的精神,尝试复制您遇到的确切错误。提供一个例子可能有帮助,但也许您正在做以下操作:
x <- c(1,2)
y <- c("a","b","c")
names(x) <- y
Error in names(x) <- y :
'names' attribute [3] must be the same length as the vector [2]
我怀疑你试图给一个比名称向量(y
)更短的向量(x
)命名。根据循环中你要做什么,%in%
操作符返回向量的事实可能是一个问题;考虑以下简单例子:
c1 <- c("one","two","three","more","more")
c2 <- c("seven","five","three")
if(c1%in%c2) {
print("hello")
}
接下来会发出以下警告:
Warning message:
In if (c1 %in% c2) { :
the condition has length > 1 and only the first element will be used
我希望通过下面的例子来解释错误:
> names(lenses)
[1] "X1..1..1..1..1..3"
names(lenses)=c("ID","年龄","视力","散光","泪液","分类") 出现错误:Error in names(lenses) = c("ID", "年龄", "视力", "散光", "泪液", "分类") : 'names'属性[6]的长度必须与向量[1]的长度相同
出现错误是因为属性数量不匹配。我只有一个属性,但尝试添加6个名称。在这种情况下,就会发生错误。请参见以下正确的内容:>>>>
> names(lenses)=c("ID")
> names(lenses)
[1] "ID"(身份证)
现在没有错误。
希望这能帮到你!
我曾经遇到过这样的错误并解决了它。你的数据集可能存在缺失值。每列观测值的数量也必须相同。
我因为一个愚蠢的原因遇到了同样的错误,我认为是这个原因:
在R Studio中工作时,如果您尝试将新对象分配给现有名称,并且您当前使用View()打开具有现有名称的对象,则会引发此错误。
关闭“View”面板,然后它就可以正常工作了。
traceback()
。 - Tommy