# [R] There must be a smarter way

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Fri Jan 28 06:42:29 CET 2011

```> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of eric
> Sent: Thursday, January 27, 2011 7:07 PM
> To: r-help at r-project.org
> Subject: [R] There must be a smarter way
>
>
> Newbie and trying to learn the right way of doing things in R. in this
> case,
> I just have that feeling that my convoluted line of code is way more
> way.
>
> I want to do something pretty simple. I have a dataframe called x that
> is
> 6945 elements long. I'd like to create a vector rtn=
> log(x[2,2]/x[1,3]),
> then log(x[3,2]/x[2,3]), then log(x[4,2]/lx[3,3])
> ...log(x[6945,2]/x[6944,3]). Also want to put zero as the first
> element.
>
> I know I can do it with a loop but I'd like to figure out the simple
> way to
> vectorize it. Here's my solution (it works but it's sure complicated
> looking) :
>
> rtn <-c(0,log(x[2:length(x[,1]),2]/x[1:length(x[,1])-1,3]))
>
> Here's what x looks like:
>
>         Date  Open Close
> 1 03/30/1983 29.96 30.35
> 2 03/31/1983 30.35 30.24
> 3 04/04/1983 30.25 30.39
> 4 04/05/1983 30.45 30.66
> 5 04/06/1983 30.85 30.85
> 6 04/07/1983 30.85 31.12

rtn <-c(0,log(x[-1,2]/x[-6945,3]))

or if you want to allow for unknown length, then

rtn <-c(0,log(x[-1,2]/x[-nrow(x),3]))