1

Trying to generate a third variable, called "var", to the dataset that only has a value of 100 for the date "2010-09-24" and NA for all other time periods.

> dataset
           weight
2010-10-04  52495
2010-10-01  53000
2010-09-30  52916
2010-09-29  52785
2010-09-28  53348
2010-09-27  52885
2010-09-24  52174
2010-09-23  51461
2010-09-22  51286
2010-09-21  50968
2010-09-20  49250
> dataset=merge(dataset,var=NA)

I know I could I use the ifelse(index(dataset)=="2010-09-24",100,NA) to generate the variable. But are there any functions that one could employ to restrict the sample only to "2010-09-24" and then place the value in that right column and row?

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
gabriel
  • 399
  • 2
  • 7
  • 17

2 Answers2

2

I haven't seen merge() used this way before, and the command isn't working for me. So maybe I'm misunderstanding the question or missing something about timeseries data, but I'd do this:

1: add a new vector of NAs

dataset$var<-NA

2: index to the date you want and save the value of 100 to the variable var

dataset[dataset$date=="24-09-2010","var"]<-100

Is that what you're looking for?

Oreotrephes
  • 447
  • 1
  • 4
  • 10
1

Yes -- If you use a data type with proper time indexing such as zoo or xts.

Have a look here at SO at previous questions on these two, and/or read the vignettes in the zoo package.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Hi Dirk, I actually did load the data using the zoo package. Though I couldn't find any functions that could restrict the sample and place a determined value in the data. – gabriel Dec 30 '12 at 01:26
  • 1
    @Gabriel, If `z` is a vector zoo object then `z[as.Date("2010-01-24")] <- 100` – G. Grothendieck Dec 30 '12 at 01:49