Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Created June 14, 2020 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrdwab/30a0eeb0eb795a746d59bf116a24a8ed to your computer and use it in GitHub Desktop.
Save mrdwab/30a0eeb0eb795a746d59bf116a24a8ed to your computer and use it in GitHub Desktop.
myFun <- function(vec, find, replace) {
if (length(find) != length(replace)) stop("incompatible find/replace")
if (all(find %in% vec)) {
pos <- which(vec == find[1])
for (i in seq_along(pos)) {
ind <- pos[i]:(pos[i]+length(find)-1)
if (identical(vec[ind], find)) vec[ind] <- replace
}
} else {
message("nothing changed")
}
vec
}
@mrdwab
Copy link
Author

mrdwab commented Jun 14, 2020

Note the difference with find_subvec (https://stackoverflow.com/q/62377018/1270695).

x1 <- c(1,2,3,4,1,0,1)
x2 <- c(1,2,3,4,1,0,1,0,1)
myFun(x1, c(1, 0, 1), c(1, 1, 1))
# [1] 1 2 3 4 1 1 1
myFun(x2, c(1, 0, 1), c(1, 1, 1))
# [1] 1 2 3 4 1 1 1 1 1
myFun(x2, c(1, 0, 1), c(1, 1, 4))
# [1] 1 2 3 4 1 1 4 0 1

find_subvec <- function(invec, subvec, replace) {
  sublen <- seq_along(subvec) - 1L
  if (length(subvec) > length(invec)) return(integer(0))
  ind <- which(
    sapply(seq_len(length(invec) - length(subvec) + 1L),
           function(i) all(subvec == invec[i + sublen]))
  )
  for (i in ind) invec[i + seq_along(subvec) - 1] <- replace
  invec
}

find_subvec(x2, c(1, 0, 1), c(1, 1, 4))
# [1] 1 2 3 4 1 1 1 1 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment