在 R 中保存不同长度结果的元素

Element to save results with different length in R

我想使用agrep函数提取相似的文本字符串并将它们保存在列表或向量中,但结果长度不同(即使替换也可能长度为零),所以我得到一个错误。

如何定义列表或向量以保存结果,即使它们的长度不同?

这是一个可重现的例子:

x <- c("REF.E600J","SIN MODELO","REF.E705N","24-53793A-K","24-53646A-K","33-53633A-K",
   "REF.E522N","CON MODELO","VAR MODELO","REF.E610L")

similitud <- list()

for (i in c(1:length(x))) {
similitud[i] <- agrep(x[i],x[-i],max=3,value=T)
}
#Error and warning
Error in similitud[i] <- agrep(x[i], x[-i], max = 3, value = T) : 
replacement has length zero
In addition: Warning messages:
1: In similitud[i] <- agrep(x[i], x[-i], max = 3, value = T) :
number of items to replace is not a multiple of replacement length
2: In similitud[i] <- agrep(x[i], x[-i], max = 3, value = T) :
number of items to replace is not a multiple of replacement length
3: In similitud[i] <- agrep(x[i], x[-i], max = 3, value = T) :
number of items to replace is not a multiple of replacement length

对于列表,您使用 [[ 而不是 [ 到 assign/get 单个元素([ returns 子列表)。

for (i in c(1:length(x))) {
  similitud[[i]] <- agrep(x[i],x[-i],max=3,value=T)
}

只需将您的 similitud[i] 更改为 similitud[[i]]