Subset String by Position of Characters in R

Viewed 167

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...

4 Answers

For a single string and a single vector you can

rawToChar(charToRaw(example.string)[characters.wanted])

Output

[1] "Ape"

For a vector of characters, you can

sapply(your_vector, function(x, i) rawToChar(charToRaw(x)[i]), characters.wanted)

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"

There's a function in the package "Biostrings" that allows you to do this.

You first have to install BiocManger

if (!require("BiocManager", quietly = TRUE))
     install.packages("BiocManager")
BiocManager::install(version = "3.14")

Next install and load the package "Biostrings"

BiocManager::install("Biostrings")
library(Biostrings)

You can then use the function letter() to subset your string. For example:

x <- "abcde"
letter(x, 1:2)

"ab"

You could use:

example.string <- "ApplesAndCookies"
characters.wanted <- c(1,3,5)

paste(strsplit(example.string, "")[[1]][characters.wanted], collapse="")

Output:

[1] "Ape"
Related