Skip to content
Prev 278376 / 398502 Next

Looping and paste

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)
[1] TRUE

# Put them to the test:
user  system elapsed
   0.67    0.00    0.67
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: