Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lagging using shift throws error if data.table has only 1 row #1014

Closed
ashinm opened this issue Jan 20, 2015 · 0 comments
Closed

lagging using shift throws error if data.table has only 1 row #1014

ashinm opened this issue Jan 20, 2015 · 0 comments
Assignees
Labels
Milestone

Comments

@ashinm
Copy link

ashinm commented Jan 20, 2015

Hi I am trying to create a data.table with lagged variables by group id. Certain id's have only 1 row in the data.table in that case the shift operator for lag gives error but the lead operator works fine. Here is an example

dt = data.table(id = 1, week = as.Date('2014-11-11'), sales = 1)
lead = 2
lag = 2
lagSalesNames = paste('lag_sales_', 1:lag, sep = '')
dt[,(lagSalesNames) := shift(sales, 1:lag, NA, 'lag'), by = list(id)]

This gives me the following error

# All items in j=list(...) should be atomic vectors or lists. If you are trying something like 
# `j=list(.SD,newcol=mean(colA))` then use `:=` by group instead (much quicker), or 
# `cbind` or `merge` afterwards.

But if I try the same thing with lead instead, it works fine

dt[,(lagSalesNames) := shift(sales, 1:lag, NA, 'lead'), by = list(id)]

It also seem to work fine if the data.table has more than 1 row e.g. you can try the following with 2 rows which works fine

dt = data.table(id = 1, week = as.Date(c('2014-11-11', '2014-11-11')), sales = 1:2)
dt[,(lagSalesNames) := shift(sales, 1:lag, NA, 'lag'), by = list(id)]

I am using data.table version 1.9.5 on a linux machine with R version 3.1.0. Any help would be much appreciated.

Thanks,
Ashin

@arunsrinivasan arunsrinivasan self-assigned this Jan 20, 2015
@arunsrinivasan arunsrinivasan added this to the v1.9.6 milestone Jan 20, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants