I have a unique character, each letter follows a number. For example:A1B10C5
A1B10C5
I would like to split it into letter <- c(A, B, C)and number <- c(1, 10, 5)using R.
letter <- c(A, B, C)
number <- c(1, 10, 5)
We can use regular expressions to separate letters and numbers.
v1 <- strsplit(str1, "(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])", perl = TRUE)[[1]] v1[c(TRUE, FALSE)] #[1] "A" "B" "C" as.numeric(v1[c(FALSE, TRUE)]) #[1] 1 10 5
str1 <- "A1B10C5"
str_extract_all is another way:
str_extract_all
library(stringr) > str <- "A1B10C5" > str [1] "A1B10C5" > str_extract_all(str, "[0-9]+") [[1]] [1] "1" "10" "5" > str_extract_all(str, "[aA-zZ]+") [[1]] [1] "A" "B" "C"
R regmatches gregexpr:
regmatches
gregexpr
regmatches(this, gregexpr("[0-9]+", "A1B10C5")) [[1]] [1] "1" "10" "5" regmatches(this, gregexpr("[A-Z]+", "A1B10C5")) [[1]] [1] "A" "B" "C"
, . akrun, [[1]] , :
[[1]]
as.numeric(regmatches(this, gregexpr("[0-9]+", this))[[1]])
To extract letters and numbers at the same time, you can use str_match_allto get letters and numbers in two separate columns:
str_match_all
library(stringr) str_match_all("A1B10C5", "([a-zA-Z]+)([0-9]+)")[[1]][,-1] # [,1] [,2] #[1,] "A" "1" #[2,] "B" "10" #[3,] "C" "5"