[R] concatenate values in the vector

Cristian Montes cmontes at arauco.cl
Wed Aug 4 00:01:57 CEST 2010


Ok, sorry, I misinterpreted the question!  Here is the right solution

x <- c("a", "b", "c", "d", "e")
z <- x[1]

for (i in 2:length(x))
    {
     z<- paste(z, x[i], sep = "+")
    }

print(z)

[1] "a+b+c+d+e"

Cheers,

Cristián.

-----Mensaje original-----
De: David Winsemius [mailto:dwinsemius at comcast.net] 
Enviado el: Martes, 03 de Agosto de 2010 05:26 p.m.
Para: Cristian Montes
CC: Henrique Dallazuanna; r-help
Asunto: Re: [R] concatenate values in the vector


On Aug 3, 2010, at 5:17 PM, Cristian Montes wrote:

> Even shorter is
>
> x<-c("a","b","c","d")
> paste(x, sep="+")

[1] "a" "b" "c" "d"

Except for the fact that it does not deliver what the OP appeared to  
be asking for. The paste function is vectorized, so if you give it a  
vector of length 4, it returns a vector of length 4. What was  
requested, at least up to the ambiguity left by no quotes around the  
requested ouput, was a single string.

-- 
David.

> Cheers,
>
> Cristian Montes
>
> -----Mensaje original-----
> De: r-help-bounces at r-project.org [mailto:r-help-bounces at r- 
> project.org] En nombre de Henrique Dallazuanna
> Enviado el: Martes, 03 de Agosto de 2010 04:37 p.m.
> Para: phoebe kong
> CC: r-help
> Asunto: Re: [R] concatenate values in the vector
>
> Try this:
>
> paste(x, collapse = '+')
>
> On Tue, Aug 3, 2010 at 5:34 PM, phoebe kong <sityeekong at gmail.com>  
> wrote:
>
>> Hi all,
>>
>> Is there a function that allow me to concatenate each value in a
>> vector to a string?
>>
>> x<-c("a","b","c","d")
>>
>> output string = a+b+c+d
>>
>> Thanks,
>> phoebe
>>
>>       [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> 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.
>>
>
>
>
> --
> Henrique Dallazuanna
> Curitiba-Paraná-Brasil
> 25° 25' 40" S 49° 16' 22" O
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list