R:当两个事件(列)都为真时,参考其中一个来决定值

R: when both events (columns) are true, refer to one of them to decide the value

我想操作 R 中的两列,以便当两个事件都为真时,引用其中一列来确定值。例如:

a<- c(0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0)
b<- c(0,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0)

当a和b都为真时,在a[9]和a[10]处,参考b来决定后面几行中另一列c的值。然后,如果 b 在某行为 FALSE,(这里是第 17 行)再次检查 a 和 b 是否为真。因此,所需的输出是这样的:

c<- c(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0)
data <- cbind(a,b,c)
data
      a b c
 [1,] 0 0 0
 [2,] 0 1 0
 [3,] 0 1 0
 [4,] 0 0 0
 [5,] 0 0 0
 [6,] 1 0 0
 [7,] 1 0 0
 [8,] 1 0 0
 [9,] 1 1 1
[10,] 1 1 1
[11,] 0 1 1
[12,] 0 1 1
[13,] 0 1 1
[14,] 0 1 1
[15,] 0 1 1
[16,] 0 1 1
[17,] 0 0 0
[18,] 0 0 0

由于数据来自多行,我更喜欢使用像 ifelse() 这样的向量化方法来处理这个问题。

非常感谢所有可以帮助我的人。

我不是 100% 确定我理解这个问题,但这里有一个重现输出的 tidyverse 解决方案:

a<- c(0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0)
b<- c(0,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0)
df <- data.frame(a,b)

library(tidyverse)
df %>% mutate(c=case_when(
  a == 1 & b == 1 ~ 1,
  a == 0 & b == 0 ~ 0,
  TRUE ~ NA_real_
)) %>% fill(c)

#    a b c
# 1  0 0 0
# 2  0 1 0
# 3  0 1 0
# 4  0 0 0
# 5  0 0 0
# 6  1 0 0
# 7  1 0 0
# 8  1 0 0
# 9  1 1 1
# 10 1 1 1
# 11 0 1 1
# 12 0 1 1
# 13 0 1 1
# 14 0 1 1
# 15 0 1 1
# 16 0 1 1
# 17 0 0 0
# 18 0 0 0