[R] eager to learn how to use "sapply", "lapply", ...

0 views
Skip to first unread message

mau...@alice.it

unread,
Apr 26, 2009, 1:42:48 PM4/26/09
to r-h...@stat.math.ethz.ch
After a year my R programming style is still very "C like".
I am still writing a lot of "for loops" and finding it difficult to recognize where, in place of loops, I could just do the
same with one line of code, using "sapply", "lapply", or the like.
On-line examples for such high level function do not help me.
Even if, sooner or later, I am getting my R scripts to do what I expect, I would really like to shake my C programming style off.
I am staring at my R script and thinking "how can I improve it ?"
For instance, I have a lot of loops similar to the following one and wonder whether I can replace them with a proper call to a high level R function that does the same:

Nstart <- Nfour/(2^Lev) + 1
Nfinish <- Nstart -1 + Nfour/(2^Lev)
LengLev <- Nfinish - Nstart + 1
NW <- floor(LengLev*N/Nfour)
if(NW > 0){
for(j in Nstart:(Nstart + NW -1)){
Dw <- abs(Y[j])
Rnorm <- Rnorm + Dw^2
}
}


Thank you very much for helping me get better.
Maura

tutti i telefonini TIM!


[[alternative HTML version deleted]]

______________________________________________
R-h...@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.

jim holtman

unread,
Apr 26, 2009, 2:04:26 PM4/26/09
to mau...@alice.it, r-h...@stat.math.ethz.ch
I think you can replace your 'for' loop with vectorized operations:

if(NW > 0){
Rnorm <- Rnorm + sum(abs(Y[Nstart:(Nstart + NW - 1)]) ^ 2)
}

--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?

Gabor Grothendieck

unread,
Apr 26, 2009, 2:28:13 PM4/26/09
to mau...@alice.it, r-h...@stat.math.ethz.ch
Also you don't need the abs since you are
squaring it anyways and seq with length
argument is a bit cleaner:

ix <- seq(Nstart, length = NW)
sum(Y[ix]^ 2)

Also please read the last line on every
message to r-help. The code in your
post lacks all 4 of the asked for
ingredients: 1. there are no comments,
2. it has lines not subsequently used
(not minimal), 3. it not self-contained
and 4. there is no reproducible
calculation.

hadley wickham

unread,
Apr 26, 2009, 6:53:45 PM4/26/09
to mau...@alice.it, r-h...@stat.math.ethz.ch
Have a look at the plyr package and associated documentation -
http://had.co.nz/plyr

Hadley

--
http://had.co.nz/

Reply all
Reply to author
Forward
0 new messages