[R] separate numbers from chars in a string
marc_schwartz at me.com
Wed Jul 30 22:52:35 CEST 2014
On Jul 30, 2014, at 3:13 PM, carol white <wht_crl at yahoo.com> wrote:
> If I have a string of consecutive chars followed by consecutive numbers and then chars, like "absdfds0213451ab", how to separate the consecutive chars from consecutive numbers?
> grep doesn't seem to be helpful
> grep("[a-z]","absdfds0213451ab", ignore.case=T)
>  1
> grep("[0-9]","absdfds0213451ab", ignore.case=T)
>  1
grep() will only tell you that a pattern is present. You want to use gsub() or similar with back references to return parts of the vector.
Will they ALWAYS appear in that pattern (letters, numbers, letters) or is there some level of variation?
If they will always appear as in your example, then one approach is:
> strsplit(gsub("([a-z]+)([0-9]+)([a-z]+)", "\\1 \\2 \\3", "absdfds0213451ab"), " ")
 "absdfds" "0213451" "ab"
The initial gsub() returns the 3 parts separated by a space, which is then used as the split argument to strsplit().
If there will be some variation, you can use multiple calls to gsub() or similar, each getting either the letters or the numbers.
More information about the R-help