Reputation:
I have a dataframe with one column:
x = data.frame(col = c('PS-01','PS-02','PS-03','PS-04','PS-05','PS-06')
)
I want to substring it with stringr and get new dataframe with int after PS- which lookslike this:
x_new = data.frame(col = c(01,02,03,04,05,06)
How could i do that?
Upvotes: 0
Views: 34
Reputation: 8127
This should do
gsub("PS-", "", x)
gsub()
searches in x
for the first argument("PS-"
) and replaces it with the second argument (""
).
And here the stringr
version:
library(stringr)
str_replace(x, "PS-", "")
Upvotes: 1
Reputation: 389315
We can use stringr
's str_extract
stringr::str_extract(x$col, "(?<=PS-)\\d+")
#[1] "01" "02" "03" "04" "05" "06"
Or using the same pattern in base R :
unlist(regmatches(x$col, gregexpr("(?<=PS-)\\d+", x$col, perl = TRUE)))
Upvotes: 1