[R] paste adjacent elements matching string
David Winsemius
dwinsemius at comcast.net
Sat Dec 5 03:50:06 CET 2009
On Dec 4, 2009, at 8:42 PM, Jill Hollenbach wrote:
> Hi all,
> I would like to combine elements of a vector:
>
> vec <- c("astring", "b", "cstring", "d", "e")
>> vec
> [1] "astring" "b" "cstring" "d" "e"
>
> such that for every element that contains "string" at the end, it is
> combined with the next element, so that I get this:
>
>> res
> [1] "astringb" "cstringd" "e"
>
It will be problematic if there are two "string" elements in a row,
but if you can assure me that is not so, then this may suffice:
> res <- vec
# First do the pasting
> res[grep("string", vec)] <- paste(vec[grep("string",
vec)],vec[grep("string", vec)+1],sep="")
# Now need to remove the strings which were concatenated to the prior
ones
> res <- res[-(grep('string', res)+1)]
> res
[1] "astringb" "cstringd" "e"
> Any help is much appreciated, still learning.
>
As are we all. Why do you think we do this?
> Many thanks,
> Jill
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list