R:对于具有不同标准的循环,用相同数据填充2个向量

时间:2017-08-16 13:04:28

标签: r for-loop vector

编写R代码以在火车上的wi-fi系统上填充2个向量和数据。

(最终用接收数据向量填充数据的空向量)

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

(每个包含2800个值的向量)     纬度&lt; - ts01 $ lat     收到&lt; - ts01 $ tprx

(如果火车向北移动,用来自接收矢量的数据填充移动的北向量)

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

(如果火车向南移动,请使用收到的矢量数据填充移动的南向量)

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

问题在于movenorth和movingsouth向量正在填充相同的数据。移动的北向量在运行代码后包含632个值,向南移动包含109,但这109个值与移动北方的前109个值匹配。显然,火车不能同时向北和向南移动。

2 个答案:

答案 0 :(得分:2)

你不需要循环,让我们看看这个玩具示例:

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

答案 1 :(得分:2)

你不应该为此使用循环。它可以通过矢量化方式轻松完成:

#reproducible example
set.seed(42)
latitude <- sample(20, replace = TRUE)
#[1] 19 19  6 17 13 11 15  3 14 15 10 15 19  6 10 19 20  3 10 12
received <- rnorm(20)
#[1]  1.3048697  2.2866454 -1.3888607 -0.2787888 -0.1333213  0.6359504 -0.2842529 -2.6564554 -2.4404669  1.3201133
#[11] -0.3066386 -1.7813084 -0.1719174  1.2146747  1.8951935 -0.4304691 -0.2572694 -1.7631631  0.4600974 -0.639994

#find directions, be a bit fuzzy around zero, adjust for precision of latitudes if necessary
direction <- cut(diff(latitude), c(-Inf, -1e-16, 1e-16, Inf), c("south", "neither", "north")) 
#[1] neither south   north   south   south   north   south   north   north   south   north   north   south   north   north  
#[16] north   south   north   north  
#Levels: south neither north

#split the vector (after discarding last value)
split(head(received, -1), direction)
#$south
#[1]  2.2866454 -0.2787888 -0.1333213 -0.2842529  1.3201133 -0.1719174 -0.2572694
#
#$neither
#[1] 1.30487
#
#$north
#[1] -1.3888607  0.6359504 -2.6564554 -2.4404669 -0.3066386 -1.7813084  1.2146747  1.8951935 -0.4304691 -1.7631631
#[11]  0.4600974

#if neither needs to be combined with north
head(received, -1)[direction %in% c("neither", "north")]
#[1]  1.3048697 -1.3888607  0.6359504 -2.6564554 -2.4404669 -0.3066386 -1.7813084  1.2146747  1.8951935 -0.4304691
#[11] -1.7631631  0.4600974