0

related question link

Hi, I have created a lagged variable using instructions from the answer to the above question (link above). It says that to create a lagged variable I need to use:

library(data.table)
 data = data[, lag.value:=c(NA, value[-.N]), by=groups]

Or, alternatively:

data = data[, lag.value :=  shift(value, 1L), keyby = groups]

This is what I got from the related questions answers below:

related question 1 link

(I might be not entirely right with the second method because it is a bit complicated there so please correct me if it's wrong)

In any case as I use any of these methods I get an error:

Error in `[.data.frame`(data, , `:=`(lag.value, c(NA,  : 
  unused argument (by = groups)

Could you please explain what I'm doing wrong here and what I should do to avoid the error?

data:

time  value   groups  
1      3        a
2      3        a
3      4        a
4      4        a
1      1        b
2      2        b
3      5        b
4      5        b

and the variable I want to create is lag.value which is value lagged by 1 within groups

Community
  • 1
  • 1
olga
  • 99
  • 9
  • I have installed the data.table package, but it's version is 1.9.4, and not 1.9.5 which seems to be necessary from what I understand for the second method. I'm also not sure why the package does not install with the highest current version? – olga Dec 03 '15 at 16:58
  • What does your data looks like ? – etienne Dec 03 '15 at 16:59
  • 4
    I think your `data` is not of class `data.table`. You can do `setDT(data)` to make sure. – Frank Dec 03 '15 at 17:04
  • Yes, I think my data is data.frame . Is setting it to data.table not going to change anything else in the way I use it (accessing data etc)? – olga Dec 03 '15 at 17:11
  • Ok, so from what I have read here: [link](http://stackoverflow.com/a/18002500/3745924) data.table is an extension of data.frame, so It will be fine to change it without losing any functionality. Thanks, and this solves it @Frank – olga Dec 03 '15 at 17:33
  • 2
    Glad that solved it. All the functionality is still available, but some of the syntax is different, like `DF[x]` and `DT[x]` will do different things; and `DF[,y]` vs `DT[,y]` I would recommend having a look at the intro docs for the package: https://github.com/Rdatatable/data.table/wiki/Getting-started – Frank Dec 03 '15 at 17:36
  • also use 1.9.6 version, it is already available on CRAN – jangorecki Dec 03 '15 at 19:40

0 Answers0