[R] String manipulation

William Dunlap wdunlap at tibco.com
Mon Dec 8 22:13:23 CET 2014


strsplit(split=":") does almost what you want, but it omits the colons from
the output.  You can use perl zero-length look-ahead and look-behind
operators in the split argument to get the colons as well:

> strsplit(c(":sad", "happy:", "happy:sad"), split="(?<=:)|(?=:)",
perl=TRUE)
[[1]]
[1] ":"   "sad"

[[2]]
[1] "happy" ":"

[[3]]
[1] "happy" ":"     "sad"



Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Mon, Dec 8, 2014 at 9:08 AM, Gang Chen <gangchen6 at gmail.com> wrote:

> I want to do the following: if a string does not contain a colon (:),
> no change is needed; if it contains one or more colons, break the
> string into multiple strings using the colon as a separator. For
> example, "happy:" becomes
>
> "happy" ":"
>
> ":sad" turns to
>
> ":" "sad"
>
> and "happy:sad" changes to
>
> "happy" ":" "sad"
>
> How to do this?
>
> Thanks,
> Gang
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list