满足条件语句后复制值?

时间:2017-04-11 03:51:10

标签: r

所以这是我的一些样本数据:

signal1   signal2   signal3   
1         0         1        
1         1         1  
1         0         1  
1         0         1  
1         0         1  
1         0         1  
1         0         0 

我想添加第四列,这样每当signal1==signal2==signal3都为1时,新列重复1秒,直到signal3从1变为0。

所以从上面的例子中,我想生成类似的东西:

signal1   signal2   signal3   signal_generate
1         0         1         0
1         1         1         1
1         0         1         1
1         0         1         1
1         0         1         1
1         0         1         1
1         0         0         0

我认为这可以通过ifelse声明来实现,但我在这个看似简单的任务上遇到了很多困难。我正在考虑做一些事情:

signal_generate <- ifelse(data[,1]==data[,2]&data[,3]>0, rep(data[,3]==1), 0)

但我无法弄清楚如何让signal3重复正确的次数。

编辑:我意识到ifelse会很愚蠢,因为它只会查看条件signal1 == signal2 == signal3完全符合的行。我仍然非常困难,非常感谢帮助!

1 个答案:

答案 0 :(得分:1)

Replacing NAs with latest non-NA value

的帮助下

我不确定初始条件是否正确处理。

df <- read.table(text="
signal1   signal2   signal3   
1         0         1        
1         1         1  
1         0         1  
1         0         1  
1         0         1  
1         0         1  
1         0         0
", header=TRUE)

library(zoo)

# apply the logic using RowSums as a shortcut
df$triple <- as.integer((rowSums(df[,1:3])) == 3L)

# detect the change in signal and sett the initial condition
df$signal_change <- ifelse(df$triple == 1L, 1L, ifelse(df$signal3 == 0L, 0, NA))
df$signal_change[1] <- df$triple[1]

# generate the signal by carryign forward the changes
df$signal_generate <- na.locf(df2$signal_change, na.rm=FALSE)
df$signal_generate[1] <- df$signal_change[1]

df

#   signal1 signal2 signal3 triple signal_change signal_generate
# 1       1       0       1      0             0               0
# 2       1       1       1      1             1               1
# 3       1       0       1      0            NA               1
# 4       1       0       1      0            NA               1
# 5       1       0       1      0            NA               1
# 6       1       0       1      0            NA               1
# 7       1       0       0      0             0               0