[R] need help with strsplit function

Marc Schwartz marc_schwartz at me.com
Thu Jun 11 19:11:23 CEST 2009


On Jun 11, 2009, at 10:44 AM, njhuang86 wrote:

>
> Hi, if I have this string: "a.b.c.d" and I use this function:
> unlist(strsplit("a.b.c.d", "\\.")), I get this as my output: "a",  
> "b", "c",
> and "d". Is there a way to just split on the first period so I  
> obtain only
> two pieces like: "a" and "b.c.d"? Anyways, thanks in advance!


Try this:

 > strsplit(sub("\\.", "*", "a.b.c.d"), "\\*")
[[1]]
[1] "a"     "b.c.d"


The inner sub() replaces the first '.' with a '*' allowing you to  
split on the unique character. You can modify the replacement  
character as your data may actually require.

HTH,

Marc Schwartz




More information about the R-help mailing list