I can't seem to find an elegant solution to a relatively simple problem in R. I would like to extract characters from a string based on a vector of positions. For example, how could I extract the 1st, 3rd, and 5th characters from example.string? substr does not work without a beginning and end.
example.string <- "ApplesAndCookies"
characters.wanted <- c(1,3,5)
Expected output would be:
Ape
I can design a loop or function to do this, but there has to be an easier way...
CodePudding user response:
A possible solution for a single string.
example.string <- "ApplesAndCookies"
characters.wanted <- c(1,3,5)
paste(unlist(strsplit(example.string, ''))[characters.wanted], collapse = '')
# ---------------------------------------------------------------------------
[1] "Ape"
Extension to a vector of strings.
example.string <- c("ApplesAndCookies","ApplesAndCookies","ApplesAndCookies")
characters.wanted <- c(1,3,5)
sapply(strsplit(example.string, ''), function(x) {
paste(x[characters.wanted], collapse = '')
})
# ---------------------------------------------------------------------------
[1] "Ape" "Ape" "Ape"
CodePudding user response:
For a single string and a single vector you can
rawToChar(charToRaw(example.string)[characters.wanted])
Output
[1] "Ape"
CodePudding user response:
You could use:
example.string <- "ApplesAndCookies"
characters.wanted <- c(1,3,5)
paste(strsplit(example.string, "")[[1]][characters.wanted], collapse="")
Output:
[1] "Ape"
