[R] There must be a smarter way

eric ericstrom at aol.com
Fri Jan 28 04:07:04 CET 2011


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
-- 
View this message in context: http://r.789695.n4.nabble.com/There-must-be-a-smarter-way-tp3243651p3243651.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list