User247365 User247365 - 1 year ago 69
R Question

Split String after first character

I have a column in a data frame like so:


I want to be able to split the column so that the first entry (which is always a single character) is separated from the rest of the entry (which is always numeric, but is of different lengths depending on the entry)

I want to do basically exactly this except after the first entry instead of the 5th and in R instead of php.

split string after x characters

Answer Source

You can use substring

x <- c("D0.5", "A4", "C1.3", "B2.0")

substring(x, 1, 1)

[1] "D" "A" "C" "B"

To get only the numeric part:

as.numeric(substring(x, 2, nchar(x)))

[1] 0.5 4.0 1.3 2.0

Or using stringi:

as.numeric(stringi::stri_sub(x, 2))

and using stringr:

as.numeric(stringr::str_sub(x, 2))

For both stringi and stringr, 2 represents the starting position. You can include the end position if you want to, else it is the last character by default.