在R中交换用户定义的连续值

时间:2015-05-29 13:35:59

标签: r vector

给定一个向量,我想在特定元素连续时交换值。

x <- c("A", "B", "C")

我想制定一个规则,如果&#34; B&#34;在&#34; C&#34;之前,然后交换值。

x <- c("A", "B", "C")
res
[1] "A" "C" "B"

如果&#34; T&#34;来之前&#34; U&#34;,

y <- c("T", "U", "X", "A", "U")
res2
[1] "U" "T" "X" "A" "U"

更广泛地适用于多场比赛。在这里,如果&#34; D&#34;直接在&#34; B&#34;,

之前
z <- c("A", "D", "B", "X", "D", "B")
res3
[1] "A" "B" "D" "X" "B" "D"

2 个答案:

答案 0 :(得分:3)

这样的功能不是很优雅,但应该可以正常工作

swap<-function(x, pair) {
    stopifnot(length(pair)==2)
    a1 <- which(x==pair[1])
    a2 <- which(x==pair[2])
    if (length(a1<-a1[a1 %in% (a2-1)])) {
        x[a1] <- pair[2]
        x[a1+1] <- pair[1]
    }
    x
}

z <- c("A", "D", "B", "X", "D", "B")
swap(z, c("Z","D"))    #no change
# [1] "A" "D" "B" "X" "D" "B"
swap(z, c("A","D"))    #one change
# [1] "D" "A" "B" "X" "D" "B"
swap(z, c("D","B"))    #multi-change
# [1] "A" "B" "D" "X" "B" "D"

答案 1 :(得分:1)

我把它分成了两个不同的功能

switchup <- function(vec, first=1, second=2) {
  vec[c(first,second)] <- vec[c(second,first)]
  return(vec)
}
swap.match <- function(v, source.pattern, stray.pattern) {
  host   <- which(v==source.pattern)
  target <- which(v==stray.pattern)
  hits <- target[which(v[host-1]==stray.pattern)]
  hits <- as.vector(na.omit(hits))
  switchup(v, hits, hits+1)
}

swap.match(x, "C", "B")
[1] "A" "C" "B"
swap.match(y, "U", "T")
[1] "U" "T" "X" "A" "U"
swap.match(z, "B", "D")
[1] "A" "B" "D" "X" "B" "D"

Mr.Flick的解决方案在更多情况下起作用。