矢量数据对元素湮灭

时间:2018-06-09 12:32:23

标签: r

示例1:

说我有fortify.zoo(r)向量:

input1

我想要的输出:

input1 <- c("A","A","X","B","Y")

每个"A" 的每个"X"将从右到左在向量方向上消除每个"A" 最近,同样,"Y"消除{{ 1}}。

示例2:

"B"

我想要的输出是:

input2 <- c("A","A","B","X","B","B","Y","A","B","B","B","X","X")

我的想法是使用"B","B","B","B","B" which来查找索引位置,但我不确定如何继续

match

如何处理长向量问题,例如上面的示例2,其中#find "A" position: which(match(c("A","A","X","B","Y"), "A") %in% 1) #find "B" position: which(match(c("A","A","X","B","Y"), "B") %in% 1) #find "X" position: which(match(c("A","A","X","B","Y"), "X") %in% 1) #find "Y" position: which(match(c("A","A","X","B","Y"), "Y") %in% 1) "A" "B""X"之间的随机序列

1 个答案:

答案 0 :(得分:1)

这将满足您的需求。它在字符串中向后工作,将每个X / Y和最近的A / B设置为NA,然后删除所有NA s ...

input <- c("A","A","B","X","B","B","Y","A","B","B","B","X","X")

annihilate <- function(x){
  for(i in rev(seq_along(x))){
    if(is.na(x[i])) next
    if(x[i]=="X") {
      x[i] <- NA
      x[tail(which(x[1:i]=="A"), 1)] <- NA
    } else if(x[i]=="Y") {
      x[i] <- NA
      x[tail(which(x[1:i]=="B"), 1)] <- NA
    } 
  }
  return(x[!is.na(x)])
}

annihilate(input)
[1] "B" "B" "B" "B" "B"