我将在R中计算曼哈顿距离,但我有一个问题,如何检查哈希中是否存在密钥。
我的代码如下。我得到的错误符合if
声明。
library("hash")
h <- hash( list( Tom=list( Film1=4.0, Film2=1.0, Film3=4.0, Film4=4.0, Film5=1.0 ), Jon=list( Film1=3.0, Film2=5.0, Film3=4.0, Film4=2.5, Film5=3.0 ) ) )
manhattan_dist <- function(rating1, rating2){
distance <- 0
for(key in rating1){
if( has.key( key, rating2 ))
distance <- distance + (abs(rating1[[1]] - rating2[[1]]))
}
return(distance)
}
dist <- manhattan_dist(h$Tom, h$Jon)
dist
错误是:
错误(函数(classes,fdef,mtable): 无法为签名'“numeric”,“list”'
找到函数'has.key'的继承方法答案 0 :(得分:1)
应该像这样工作
manhattan_dist <- function(rating1, rating2){
distance <- abs(rating1-rating2)
distance <- sum(distance)
return(distance)
}