Search code examples
rfor-loopcoordinates

How to make a for with more than one else if in R?


I want to associate points in these coordinates and associate them with the correspondent number. However every time I tried to run it I got this: the condition has length > 1

for (i in dados) {
    if (dados[dados$latitude>="55.84" & dados$latitude<= "55.95" & dados$longitude>="-3.444" & dados$longitude<="-3.198", ]){
      dados$neighbourhood <- 1
    } else if (dados[dados$latitude>="55.84" & dados$latitude<= "55.95" & dados$longitude>="-3.198" & dados$longitude<="-3.058", ]){
      dados$neighbourhood <- 2
    } else if (dados[dados$latitude>="55.95" & dados$latitude<="56.01" & dados$longitude>="-3.444" & dados$longitude<="-3.198", ]){
      dados$neighbourhood <- 3
    } else if (dados[dados$latitude>="55.95" & dados$latitude<="56.01" & dados$longitude>="-3.189" & dados$longitude<="-3.058", ]){
      dados$neigbourhod <- 4
    }
   }

Your help would be much appreciated thanks in advance.


Solution

  • Here is a vectorized way. Use the fact that binary numbers are written with 0/1 times powers of two. And add 1 to have one-based results.

    i2 <- dados$latitude >= 55.95 & dados$latitude<= 56.01
    i1 <- dados$longitude >= -3.198 & dados$longitude <= -3.058
    dados$neigbourhod <- 1 + i1 + i2*2