我想在r
中使用循环计算曼哈顿距离 Bill = c(2,3.5,2,3.5,3)
Ang = c(3.5,2,5,1.5,2)
user = cbind(Bill, Ang)
for (row in 1:nrow(user)){
for (col in 1:ncol(user)){
distance = 0
distance[row] = sum(abs(user[row,col] - user[row, col])))
}
}
我理解以下代码: 对于第一个循环:
for row equal to 1
for col equal to 1
distance = absolute sum of user[1,1] - user[1,2]
Output
#distance [1] NA NA NA NA 0
我知道以下link
中的apply和其他方法感谢您的帮助。
答案 0 :(得分:1)
不确定您正在寻找什么,也不知道曼哈顿距离是多少,但这可能会回答您的问题:
Bill <- c(2,3.5,2,3.5,3)
Ang <- c(3.5,2,5,1.5,2)
Bob <- c(4,2,5.5,1.5,3)
Dan <- c(3,2,8,2.5,6.5)
user <- as.data.frame(cbind(Bill, Ang, Bob, Dan))
### Using numeric column references ###
for (j in 2:ncol(user)) {
tmp <- c(1:nrow(user))
for (i in 1:nrow(user)) {
tmp[i] <- abs(user[i,1] - user[i,j])
}
name <- paste0("dist_", names(user)[j])
user <- cbind(user, tmp)
names(user)[names(user)=="tmp"] <- name
}