Re: [S] applying a function element-wise to two lists

Jens Oehlschlaegel (oehl@Psyres-Stuttgart.DE)
Tue, 14 Apr 1998 21:28:08 +0200 (MET DST)


I would like to re-post the question based upon the following
observations:

# here is a simplified example (done in WinS+4.0 Release3, Win95,
Pentium133, 64MB)
# of course this specific task is done much more efficiently without lists
at all, see below

n <- 10000
y <- x <- as.list(1:n)

# that was the loop alternative discussed
# where z violates the "avoid growing lists" principle
a <- proc.time()
z <- list ()
for (i in 1:length(x))z[[i]] <- x[[i]]*y[[i]]
b <- proc.time()
b-a
# 24 sec

# avoiding growing list z (probably) saves memory
# but is even slower, I assume because
# there is no real replacement for list elements in S+
# in fact each z[[i]]<- causes the whole z to be replaced
a <- proc.time()
z <- vector("list",length(x))
for (i in 1:length(x))z[[i]] <- x[[i]]*y[[i]]
b <- proc.time()
b-a
# 44 sec

# the lapply solution discussed was faster but is far from being
# efficient, since the called function receives
# the whole objects x and y as parameters each call
# and not only the needed parts x[[i]] and y[[i]]
a <- proc.time()
z <- lapply(seq(along=x), function(i,x2,y2){x2[[i]]*y2[[i]]} , x, y)
b <- proc.time()
b-a
# 13.5 sec

# thus not passing x and y as parameters should
# save some memory and do a little faster
a <- proc.time()
z <- lapply(seq(along=x), function(i){x[[i]]*y[[i]]} )
b <- proc.time()
b-a
# 12 sec

# However, is this really S+'s best solution with two lists?
# It is incredibly slow compared to the real task's solution!
x <- y <- 1:n
a <- proc.time()
z <- x*y
b <- proc.time()
b-a
# 2.5 sec

Best regards

Jens Oehlschlaegel

--
Jens Oehlschlaegel-Akiyoshi
Psychologist/Statistician
Project TR-EAT + COST Action B6
                                                 F.rankfurt
oehl@psyres-stuttgart.de                         A.ttention
+49 711 6781-408 (phone)                         I.nventory
+49 711 6876902  (fax)                           R .-----.
                                                  / ----- \
Center for Psychotherapy Research                | | 0 0 | |
Christian-Belser-Strasse 79a                     | |  ?  | |
D-70597 Stuttgart Germany                         \ ----- /
-------------------------------------------------- '-----' -
(general disclaimer)                             it's better

----------------------------------------------------------------------- This message was distributed by s-news@wubios.wustl.edu. To unsubscribe send e-mail to s-news-request@wubios.wustl.edu with the BODY of the message: unsubscribe s-news