Boro Dega
Boro Dega

Reputation: 393

Calculate row difference through looping

I would like to calculate the Manhattan distance using looping in 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])))
   }
 }

I understand the code to do the followings: for the first loop:

   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

I know about the apply and other methods in the following link

Thank you for your help.

Upvotes: 0

Views: 168

Answers (1)

cody_stinson
cody_stinson

Reputation: 400

Not sure exactly what you're looking for, nor do I know what Manhattan distance is, but this may answer your question:

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

}

Upvotes: 2

Related Questions