找到与条件

时间:2015-07-21 13:13:08

标签: r

我有一个数据帧,其位置在pos1,采样时间在t.s。另外,我有一个阈值/滞后,两侧(正面和负面)。

  n t.s.       pos1     pos2     pos3  X   side
  1   0  0.0000000 0.000000 0.000000 NA MIDDLE
  2  78 -0.4541016 1.430664 1.430664 NA MIDDLE
  3 109 -0.4199219 1.430664 1.430664 NA MIDDLE
  4 147 -0.4150391 1.430664 1.430664 NA MIDDLE
  5 197 -0.4345703 1.430664 1.425781 NA MIDDLE
  6 247 -0.4541016 1.430664 1.430664 NA MIDDLE

在这种情况下,滞后= 0.5 / -0.5。只要pos1> 1,就会打开一盏灯。迟滞并且它将不会转到直到pos1< -0.5。为此,我在我的数据框(侧面)中创建了附加变量,告诉我pos1是否高于0.5(ON),介于0.5和-0.5(中间)之间,或低于-0.5(OFF)。

我想制作一个只有两种可能性ON / OFF的变量(假设说光)。为此,我需要分配到两个中的一个,这取决于最后一个不同的因素(ON / OFF)。

在满足条件中间后找到函数找到前面的变量时遇到了问题。

2 个答案:

答案 0 :(得分:2)

几个小时后,我想出了这个解决方案,效率远低于你的解决方案RHertel(我猜)。它们都起作用,这是一个很好的概念证明。

data$side<-vector("character", length = lengthExp)
for(i in 1:lengthExp){
  if (data$pos1[i]>=Hysteresis)
    data$side[i]<- "ON"
  if (data$pos1[i]>= -Hysteresis && data$pos1[i]<= Hysteresis)
    data$side[i]<- "MIDDLE"
  if (data$pos1[i]<= -Hysteresis)
    data$side[i]<- "OFF"
}

data$light<-vector("character", length = lengthExp)
for(i in 1:lengthExp){
  if(i==1 && data$side[i]=="MIDDLE") data$light <- "OFF"
  if(i>1){
    if (data$side[i]== "ON")
      data$light[i]<- "ON"
    if (data$side[i]== "MIDDLE") 
      data$light[i]<- data$light[i-1]
    if (data$side[i]== "OFF")
      data$light[i]<- "OFF"
  }
}

答案 1 :(得分:1)

这是我现在可以提出的建议。给定pos1的值序列,在值pos1 < -0.5的情况下,灯的状态从ON切换到OFF,在值pos1 > 0.5的情况下,灯的状态从OFF切换到ON。 / p>

灯光的状态(ON / OFF)在变量state中编码,其中1的值为ON,0的值为OFF:

set.seed(1234)
n_length <- 100 # As an example we look at 100 consecutive states / signals
pos1 <- rnorm(n_length) # normally distributed sequence of signals with mean=0 
switch_on <- (pos1 > 0.5) # potential signals to turn on the light
switch_off <- (pos1 < -0.5) # potential switch-off signals
state <- vector(length=n_length) 
check_switch <- function(state, switch_off, switch_on){
  if(state == 1 && switch_off) state <- 0
  if(state == 0 && switch_on) state <- 1
  return(state)
}
state[1] <- 1 # the default initial state is chosen as "ON". 
state[1] <- check_switch(state[1],switch_off[1],switch_on[1])
for (i in 2:n_length){
  state[i] <- state[i-1]
  state[i] <- check_switch(state[i], switch_off[i], switch_on[i])
}
#> head(cbind(pos1,state),10)
#            pos1 state
# [1,] -1.2070657     0
# [2,]  0.2774292     0
# [3,]  1.0844412     1
# [4,] -2.3456977     0
# [5,]  0.4291247     0
# [6,]  0.5060559     1
# [7,] -0.5747400     0
# [8,] -0.5466319     0
# [9,] -0.5644520     0
#[10,] -0.8900378     0

不幸的是,这不是流行的单线矢量化解决方案的类型。我不确定它是否可以放在一个明显更短的形式,但也许有人找到一个更紧凑的答案。在任何情况下,我希望代码是有用的,并产生正确的结果。