[R] Relative subscripting

(Ted Harding) Ted.Harding at nessie.mcc.ac.uk
Tue Nov 30 22:34:02 CET 2004

On 30-Nov-04 Tobias Muhlhofer wrote:
> [...]
> I have monthly a dataset with, among other things, "marketcap",
> and "return".
> I want to multiply return by the marketcap of the previous month.
> How do I do this?
> In STATA (which I have used frequently in the past) I would simply
> use an expression of the form
> return[_n]*marketcap[_n-1]
> I believe they call this relative subscripting. Is there something
> like this in R?

Not as such, as far as I know. But there's an easy way to achieve
the same effect:


  new.var <- return[2:N]*marketcap[1:(N-1)]

1. Note the parantheses in "1:(N-1)".
     > 1:(6-1)
     [1] 1 2 3 4 5
     > 1:6-1
     [1] 0 1 2 3 4 5
   (i.e. ":" is evaluated before "-")

2. You could also define n <- 2:(N-1) in which case you could
   definitely write


   which looks very similar to what you wrote, but I don't
   know whether it implies the same underlying mechanism.

3. I'm not sure you should use "return" as the name of a variable,
   since it's a predefined function in R, which you can put in a
   function definition to tell it what to return:
     > sq<-function(x){return(x^2)}
     > sq(4)
     [1] 16

   In my experiments, it didn't seem to change this behaviour
   to assign something to "return", e.g. return<-2, even inside
   the function definition; but I'd recommend avoiding the practice!

   You could avoid it here by using "Return" instead of "return"
   for the name of your variable.

Best wishes,

E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861  [NB: New number!]
Date: 30-Nov-04                                       Time: 21:34:02
------------------------------ XFMail ------------------------------

More information about the R-help mailing list