Reputation: 685
I have a column in a data frame like so:
D0.5
A4
C1.3
B2.0
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
Upvotes: 0
Views: 7922
Reputation: 887128
We can use sub
as.numeric(sub("^.(.*)", "\\1", v1))
#[1] 0.5 4.0 1.3 2.0
Or
library(tidyr)
extract_numeric(v1)
#[1] 0.5 4.0 1.3 2.0
v1 <- c("D0.5", "A4", "C1.3", "B2.0")
Upvotes: 1
Reputation: 4965
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.
Upvotes: 4