R - extract number from string(special solution) -


i have string x <- "avd_1xx_2xx_3xx"
need extract number x(string) , put them in new variables

num1 <- 1xx
num1 <- 2xx
num1 <- 3xx

however, can't predict number of digits each number
instance, x "avd_1_2_3" or "avd_11_21_33" or likes

could give me solutions? thanks

we can use str_extract stringr. extract multiple matches use str_extract_all, returns list of length 1 (as have single element in 'x'). extract list element, can use [[ i.e. [[1]].

library(stringr) str_extract_all(x, "\\d+[a-z]*")[[1]] #[1] "1xx" "2xx" "3xx" 

a similar option using base r regmatches/gregexpr

regmatches(x, gregexpr("\\d+[a-z]*", x))[[1]] #[1] "1xx" "2xx" "3xx" 

the pattern match 1 or more numbers (\\d+) followed 0 or more lower case letters ([a-z]*).


it better keep vector rather having multiple objects in global environment.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -