# [R] Looping and paste

Dennis Murphy djmuser at gmail.com
Thu Nov 24 09:12:21 CET 2011

```Hi:

There are two good reasons why the loop solution is not efficient in
this (and related) problem(s):

(i) There is more code and less transparency;
(ii) the vectorized solution is four times faster.

Here are the two proposed functions:

# Vectorized version
m1 <- function(v) paste(v, ' to ', v + 50, ' mN', sep = '')

# Loop version:
m2 <- function(v) {
out <- rep(NA, length(v))
for(i in seq_along(v)) out[i] <- paste(v[i], ' to ', v[i] + 50,
' mN', sep = '')
out
}
BndY <- seq(from = 18900, to = 19700, by = 50)

> identical(m1(BndY), m2(BndY))
[1] TRUE

# Put them to the test:
> system.time(replicate(10000, m1(BndY)))
user  system elapsed
0.67    0.00    0.67
> system.time(replicate(10000, m2(BndY)))
user  system elapsed
2.67    0.00    2.67

The vectorized version is four times faster and produces the same
output as the loop version. Experiments with a longer test vector (501
elements) maintained the timing ratio.

Dennis

On Wed, Nov 23, 2011 at 7:00 PM, markm0705 <markm0705 at gmail.com> wrote:
> Thank you
>
> On Thu, Nov 24, 2011 at 7:31 AM, B77S [via R] <
> ml-node+s789695n4102066h98 at n4.nabble.com> wrote:
>
>> out <- vector("list")
>> Ylab <- for(i in 1:length(BndY))
>> {
>> out[i] <- paste(BndY[i]," to ",BndY[i],"mN")
>> }
>>
>> Ylab <- do.call(c, out)
>>
>>
>>
>>
>>
>>  markm0705 wrote
>> Dear R helpers
>>
>> I'm trying to make up some labels for plot from this vector
>>
>> BndY<-seq(from = 18900,to= 19700, by = 50)
>>
>> using
>>
>> Ylab<-for(i in BndY) {c((paste(i," to ",i+50,"mN")))}
>>
>> but the vector created is NULL
>>
>> However if i use
>>
>> for(i in BndY) {print(c(paste(i," to ",i+50,"mN")))}
>>
>> I can see the for loop is making the labels I'm looking for but not sure
>> on my error in assigning them to a vector
>>
>>
>>
>>
>> ------------------------------
>> below:
>> http://r.789695.n4.nabble.com/Looping-and-paste-tp4101892p4102066.html
>> .
>>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Looping-and-paste-tp4101892p4102553.html
> Sent from the R help mailing list archive at Nabble.com.
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help