0

Suppose a data.table:

z = data.table(k=1:10, h=1:100, i=1:100)
setkey(z, k)

I want to estimate for each key k, lm(h~i).

My first thought was just to try:

result = z[,lm(h~i),by=key(z)]

But this returns an error, reminding me, 'All items in j=list(...) should be atomic vectors or lists.'

Next, following the error's suggestion:

result = z[,list(lmcol=lm(h~i)),by=key(z)]

But,

result[1,class(lmcol[[1]])] 

returns 'numeric' instead of 'lm'!

What is the correct procedure for recovering the entire lm object from the second code block?

Thanks!

user220419
  • 549
  • 1
  • 4
  • 11

1 Answers1

2

Wrap everything in a list

result <- z[, list(lmcol = list(lm(h~i))), by = key(z)]

However, be warned that update etc don't work well with this approach see Why is using update on a lm inside a grouped data.table losing its model data? for a description of this problem

Community
  • 1
  • 1
mnel
  • 113,303
  • 27
  • 265
  • 254
  • Worked perfectly! For future possible visitors to this question, there's a small typo in your code block that may confuse people glancing over the question quickly. It should read `result <- z[,list(...),by=key(z)]`. – user220419 Nov 21 '13 at 03:20
  • @user220419 - noted and fixed. – mnel Nov 21 '13 at 03:21