[R] Vectorizing a function that needs to access previous elements of a row

Joshua Wiley jwiley.psych at gmail.com
Sun Nov 21 01:01:43 CET 2010


Hi Amol,

It depends on your exact needs, but one way, assuming you do not need
to access previous calculations, only previous elements:

x <- 1:10
x[-10] / x[-1]

The idea is first create a vector, x, then using negative indices,
select the first 9 elements of x (i.e., 1:9) to be divded by the last
nine (i.e., 2:10).  You are now just passing one vector of length 9 to
be divided by another and because division is already vectorized in R,
you're done.

If you actually wanted to divide through 10, you'd need to make x 1 longer:

x <- 1:11,
x[-11]/x[-1]

HTH,

Josh

On Sat, Nov 20, 2010 at 3:54 PM, Amol Shelat <shelata at gmail.com> wrote:
> Hi,
>
> I'm a newbie when it comes to R, and I'm trying to figure out how to use
> vectorization as opposed to for loops.  In particular, how can I create a
> function that is applied on each element of a row, but can access previous
> elements relative to that element?
>
> My problem: I want to calculate something like x[i] = x[i] / x[i - 1] for
> each element of a vector x:
>
> ex.
>
> x <- data.frame(a = c(1:10))
>
> # incorrect
> foo = function(y) {
>
> y[n] <- y[n] / y[n-1]
>
> }
>
> div <- lapply(x, foo)
>
> Any help would be greatly appreciated.
>
> Regards,
> -Amol Shelat
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list