[R] splitting a string up

Marc Schwartz marc_schwartz at me.com
Fri Aug 21 22:04:10 CEST 2009


On Aug 21, 2009, at 2:50 PM, stephen sefick wrote:

> x <- "1041281__2009_08_20_.lev"
>
> I would like to split this string up and only extract the leading  
> numbers.
>
> 1041281
>
> to use as a label for a data column in a bigger for loop function to
> read in data.
> regards,


At least four options:

 > gsub("_.*", "", x)
[1] "1041281"


 > gsub("^([0-9]*)_.*", "\\1", x)
[1] "1041281"


 > sapply(strsplit(x, split = "_"), "[", 1)
[1] "1041281"


 > substr(x, 1, 7)
[1] "1041281"


The fourth example presumes that the initial numeric sequence is  
always 7 characters in length. The first three do not make that  
presumption.

All will work where 'x' might contain multiple entries of a similar  
configuration as 'x'.

See ?gsub, ?regex, ?strsplit and ?substr for more information.

HTH,

Marc Schwartz




More information about the R-help mailing list