Get non-zero values from string in R

Using raw comparison:

rawToChar(as.raw(pmax(as.numeric(charToRaw(x1)), as.numeric(charToRaw(x2)))))
# [1] "13011000"

We could wrap it into a function:

foo <- function(x, y){
  mapply(FUN = function(x, y) {
    rawToChar(as.raw(pmax(as.numeric(charToRaw(x)), as.numeric(charToRaw(y)))))
  }, x = x, y = y, USE.NAMES = FALSE)
}

x1 <- "03011000"
x2 <- "13001000"
foo(x1, x2)
# [1] "13011000"

x1 <- c("03011000", "ab", "123")
x2 <- c("13001000", "cd", "212")
foo(x1, x2)
# [1] "13011000" "cd"       "223"     

The strings have an exact overlap in their non-zero characters.

I assume this means that when both strings are nonzero, they are guaranteed to match?

If so, it is sufficient to find the positions with zeros in one vector and not in the other (with setdiff) and make the string edit:

r <- gregexpr("0", c(x1,x2))
w <- setdiff(r[[1]], r[[2]])
rr <- structure(w, match.length = rep(1L, length(w)), useBytes = TRUE)

x = x1
regmatches(x, rr) <- regmatches(x2, rr)
x
# [1] "13011000"

Tags:

String

R