# [R] Incrementing a counter in lapply

Gabor Grothendieck ggrothendieck at gmail.com
Mon Mar 13 20:03:25 CET 2006

```Try this:

plot(Y ~ X, d, type = "n")
f <- function(i) abline(lm(Y ~ X, d, subset = D == i), col = colors[i+1])
junk <- lapply(unique(d\$D), f)

On 3/13/06, John McHenry <john_d_mchenry at yahoo.com> wrote:
>    Hi All,
>
>    I'm looking for some hints on idiomatic R usage using 'lapply' or similar.
>    What follows is a simple example from which to generalize my question...
>
>    # Suppose, in this simple example, I want to plot a number of different lines in different colors;
>    # I define the colors I wish to use and I plot them in a loop:
>         Y     X     D
>                85    30     0
>                95    40     1
>                90    40     1
>                75    20     0
>           100    60     1
>                90    40     0
>                90    50     0
>                90    30     1
>               100    60     1
>                85    30     1"
>    # graph the relation of Y to X when
>    #     i)  D==0
>    #     ii) D==1
>    with( d, plot(X, Y, type="n") )
>    component<- with( d, split(d, D) )
>    colors<- c("blue", "green")
>    for (i in 1:length(component))
>        with( component[[i]], lines(X, predict(lm(Y ~ X)), col=colors[i]) )
>
>    #
>    # ... seems easy enough
>    #
>    # [Q.]: How to do the same as the above but using 'lapply'?
>    # ... i.e. something along the lines of:
>    with( d, plot(X, Y, type="n") )
>    colors<- c("blue", "green")
>    # how do I get lapply to increment i?
>    lapply( with(d, split(d, D)), function(z) with(z, lines(X, predict(lm(Y ~ X)), col=colors[i])) )
>
> Thanks,
>
> Jack.
>
>
>
> ---------------------------------
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help