我正在尝试将此功能应用于数据框列:
best_recom <- function(x,n=1) {
y <- result2[x,order(-result2[x,])[n]]
inds = which(result2[x,] == y, arr.ind=TRUE)
recom <- names(inds[1])
return(recom)
}
像这样:
apply(last_visit[,2], 1, best_recom)
但我收到此错误:
dim(X) must have a positive length
我已经尝试将其应用为如下矩阵:
apply(as.matrix(last_visit)[,2],1,recomenda_n_melhor)
但是我得到了同样的错误。这些是使用的数据帧:
result2-相似度矩阵-这只是一个样本
X1.0 X1.1 X2.1 X3.1
X1.0 0.0000000 0.5000000 0.3872983 0.3162278
X1.1 0.5000000 0.0000000 0.2581989 0.0000000
X2.1 0.3872983 0.2581989 0.0000000 0.0000000
X3.1 0.3162278 0.0000000 0.0000000 0.0000000
last_visit
customer cat
1 1 X5.1
2 2 X6.1
3 3 X1.1
4 4 X2.1
发生这种情况是因为R强制last_visit[,2]
转换为无量纲向量,而R则apply
期望对象具有某些维度。您可以通过添加drop=F
命令来防止强制,即:
apply(last_visit[,2,drop=F], 1, best_recom)
另一种方法是仅仅使用lapply
或sapply
在载体:
lapply(last_visit[,2], best_recom)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句