0

I have a large vector of strings. The strings have no defining features. I want to extract whatever character is at a specific location within the string. In the following example, I would like to extract the 4th character of each of the strings:

strings <- c("01234567890", "abcdefg", ".-2dqrst")

such as the result would be

results <- c("3", "d", "d")

After extensive searching I have not been able to come up with a regex that does this, without using some fixed features of the strings, such as locations of special characters.

user6571411
  • 2,749
  • 4
  • 16
  • 29

1 Answers1

3

We can use substr in base R

substr(strings, 4, 4)
#[1] "3" "d" "d"

Or using sub

sub("^...(.).*", "\\1", strings)
#[1] "3" "d" "d"
akrun
  • 874,273
  • 37
  • 540
  • 662