[R] How to adjust the start of a series to zero? (i.e. subtract the first value from the sequence)

Peter Ehlers ehlers at ucalgary.ca
Mon Jul 2 22:51:06 CEST 2012

On 2012-07-02 12:25, David Winsemius wrote:
> On Jul 2, 2012, at 2:21 AM, Bert Gunter wrote:
>> Hi Kristina:
>> That's because I gave you the wrong function. It should be "with" not
>> "within", as:
>> sort2v4$adj_mean<-with(sort2v4, ave(mean, point, FUN=function(x)x-
>> x[1]))
>> within(dat,...) returns dat suitably modified.
>> with (dat,...) just returns the result of the function.
>> I frequently use within() when I mean with(), unfortunately.  Sorry
>> for the
>> error.
> That's interesting to me. I almost never use `within`. I'm wondering
> if I'm missing something? As I read the help page `within` is going to
> do something different when the expression is an assignment, so one
> could do the following with `within`
> within(dfrm, var2 <- var2/100)
> ... but that would have no lasting effect since its result was not
> assigned, so I do not se an advantage over:
>    dfrm$var2 <- with(dfrm, var2/100)
> In both case one would still need to assign the result to an object,
> in the case of the first to 'dfrm' itself and in the second case to
> dfrm[['var2']].
> None of the examples on the help page use `within`. Is that because it
> is inferior to transform?

I don't think that within() is inferior to transform().
I started using it after seeing some code by Bill Venables
and I now use it fairly frequently (not as frequently as the
quite useful with(), though). I think that within() can be
more versatile than transform(); consider:

  aq <- head(airquality)
  aq1 <- transform(aq, new1 = Ozone^2,
                       new2 = new1 + 10)
  #Error in eval(expr, envir, enclos) : object 'new1' not found

  aq1 <- within(aq, {new1 <- Ozone^2;
                     new2 <- new1 + 10})

I agree that, for a single new or redefined variable,
the 'df$newvar <- ...' assignment is straightforward,
but for fairly extensive modifications, within() is
very nice. The only thing that bugs me about within()
is that the new variables are appended in "reverse"

Peter Ehlers

More information about the R-help mailing list