Brad Brad - 2 years ago 42
R Question

R: For loops with different criteria filling 2 vectors with the same data

Writing R code to fill 2 vectors with the data received amounts on a wi-fi system on a train.

(Empty vectors to eventually be filled with data from received data vector)

movingnorth <- vector('numeric')
movingsouth <- vector('numeric')


(Vectors containing 2800 values each)
latitude <- ts01$lat
received <- ts01$tprx

(If the train is moving north, fill the moving north vector with data from received vector)

for(y in 1:length(latitude)){
if (y < length(latitude)){
if(latitude[y]<= latitude[y+1]){
movingnorth <- c(movingnorth, received[y])
}
else {
break()
}
}
}


(If the train is moving south, fill the moving south vector with data from received vector)

for(z in 1:length(latitude)){
if (z < length(latitude)){
if(latitude[z] >= latitude[z+1]){
movingsouth <- c(movingsouth, received[z])
}
else {
break()
}
}
}


The problem is that the movingnorth and movingsouth vectors are being filled with the same data. The moving north vector contains 632 values after running the code, and the moving south contains 109, but those 109 values match the first 109 values of moving north. Obviously, a train cannot be moving both north and south at the same time.

Answer Source

you dont need a loop, lets look at this toy example:

latitude <- c(1,2,1,3,2) # latitude coordinates
received <- 1:5

require(data.table)
d <- data.table(lat = latitude, rec = received)
d
#    lat rec
# 1:   1   1
# 2:   2   2
# 3:   1   3
# 4:   3   4
# 5:   2   5
d[, dif := c(0, diff(lat))] # if positive moved N, if negative S
movingnorth <- d[dif >= 0, rec]
movingsouth <- d[dif < 0, rec]
movingnorth
#[1] 1 2 4
movingsouth
# [1] 3 5
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download