希望编写更有效的代码,我想知道如何改进它:
此代码的目标是在时间戳中查找中断,并在每次中断时设置递增的值。
t <- structure(list(time = c(224.725, 224.783333, 224.791667, 249.925, 249.941667, 249.95, 254.091667, 254.1, 257.7, 257.708333), xpos = c(0.163348, 0.153299, 0.152359, 0.361539, 0.361141, 0.360954, 0.268117, 0.26734, 0.337446, 0.337682), ypos = c(0.324384, 0.270986, 0.263144, 0.281089, 0.281312, 0.281232, 0.230567, 0.2278, 0.213937, 0.213563), zpos = c(0.552786, 0.497958, 0.489427, 0.500912, 0.501001, 0.500993, 0.450065, 0.446757, 0.429773, 0.429488), gaps = c(NA, 0.0583330000000046, 0.00833399999999074, 25.133333, 0.016666999999984, 0.00833299999999326, 4.14166700000001, 0.00833299999999326, 3.59999999999999, 0.00833299999999326), xvel = c(NA, -0.17226955582602, -0.112790976721987, 0.00832281178146965, -0.0238795224095753, -0.0224408976359227, -0.0224153704293464, -0.093243729749262, 0.0194738888888889, 0.0283211328453317), yvel = c(NA, -0.915399516568593, -0.940964722823222, 0.000713992051909708, 0.0133797324053665, -0.00960038401537132, -0.0122329970033805, -0.332053282131553, -0.00385083333333334, -0.0448817952718454), zvel = c(NA, -0.93991394236531, -1.02363810895242, 0.000456962870782001, 0.00533989320214143, -0.000960038401537798, -0.012296498004306, -0.39697587903548, -0.00471777777777779, -0.0342013680547541)), row.names = c(26968L, 26975L, 26976L, 29992L, 29994L, 29995L, 30492L, 30493L, 30925L, 30926L), class = "data.frame")
j <- 1
t$trajectory[1] <- NA
for(i in 2:nrow(t)){
if(t$gaps[i] > 0.1){
j <- j + 1
t$trajectory[i] <- j
}else {
t$trajectory[i] <- j
}
}
答案 0 :(得分:2)
我们得到逻辑表达式(gaps > 0.1
)的累加总和,同时照顾NA
元素,或者从第二行开始,并更新已经创建的NA列“轨迹”。通过使用累积和,当表达式为TRUE
时,它将加1并保持该值,直到命中另一个TRUE
t$trajectory <- NA
t$trajectory[-1] <- with(t, cumsum(gaps[-1] > 0.1) + 1)
t$trajectory
#[1] NA 1 1 2 2 2 3 3 4 4
或者可以用
一行编写t$trajectory <- c(NA, cumsum(t$gaps[-1] > 0.1) + 1)