> -----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
> complicated than it needs to be. Please help me in seeing the easier
> 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:
>
> head(x)
> 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
How about something like
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]))
hope this is helpful,
Dan
Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA 98504-5204