vector - swapping user defined consecutive values in R -
given vector, wanted swap values when particular elements consecutive.
x <- c("a", "b", "c")
i want make rule, if "b" comes before "c", swap values.
x <- c("a", "b", "c") res [1] "a" "c" "b"
if "t" comes before "u",
y <- c("t", "u", "x", "a", "u") res2 [1] "u" "t" "x" "a" "u"
more broadly multiple matches also. here if "d" directly before "b",
z <- c("a", "d", "b", "x", "d", "b") res3 [1] "a" "b" "d" "x" "b" "d"
a function isn't elegant, should work
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"
Comments
Post a Comment