Thanks, Gabor. Reading your suggestion (and a previous one as well) I
realized I surely expressed myself quite badly when asking the
question.
Luckily one person privately suggested the following solution, which
is exactly what I was looking for:
x[time(x)==2] <- 0
This works wonderfully. However, I tested it and it is very slow. So I
am back to index arithmetic, which is fast:
x[2 - start(x)[1] + 1] <- 0
However, this is much more prone to errors than the first solution above.
I also tried to define get() and set() functions for time series as follows:
ts.get <- function(myts, i) { myts[i - start(myts)[1] + 1] }
ts.set <- function(myts, i, val) { myts[i - start(myts)[1] + 1] <- val;
myts }
Both of these work, and ts.get is quite useful. However, ts.set is
again slow due to the need to copy the whole object. So ts.set cannot
be used just as
ts.set(x, i, val)
but rather one must write
x <- ts.set(x, i, val)
In the definition of ts.set, the expression after the semicolon
returns a modified copy of the argument myts. It has to be done this
way (please let me know if there is a better and fast way) since in R
there is no way of passing arguments by reference. That is, one cannot
have side effects on the arguments of a function.
Cheers,
FS
On 4/27/05, Gabor Grothendieck <ggrothendieck at gmail.com>
wrote:>
>
>
> On 4/26/05, Fernando Saldanha <fsaldan1 at gmail.com> wrote:
> > I tried to assign values to specific elements of a time series and got
> > in trouble. The code below should be almost self-explanatory. I wanted
> > to assign 0 to the first element of x, but instead I assigned zero to
> > the second element of x, which is not what I wanted. Is there a
> > function that will allow me to do this without going into index
> > arithmetic (which would be prone to errors)?
> >
> > FS
> >
> > > x<- ts(c(1,2,3,4), start = 2)
> > > x
> > Time Series:
> > Start = 2
> > End = 5
> > Frequency = 1
> > [1] 1 2 3 4
> > > x[2] <- 0
> > > x
> > Time Series:
> > Start = 2
> > End = 5
> > Frequency = 1
> > [1] 1 0 3 4
>
>
> Any of the following will do it:
>
> x[1] <- 0
>
> # or
>
> window(x, start = 2, end = 2) <- 0
>
> # or since time 2 is at the beginning:
>
> window(x, end = 2) <- 0
>