-3

I have the following code and I would like to be able to just change 'x' and 'stat' and run the whole code. At the moment I have to manualy change 'pts' in the 5th line in the rollapply function. If I change 'pts' to 'stat' there is an error. Thanks for any help!

x = 5
stat = 'pts'
game_stats[,paste0('l',x,'g_', stat):=0]
game_stats[,paste0('l',x,'g_', stat):=NA]
game_stats[,paste0('l',x,'g_', stat):=rollapply(pts, list(-(1:x)), mean, fill=NA, align='right'),
           by=team]
jogo
  • 12,469
  • 11
  • 37
  • 42
David
  • 301
  • 1
  • 3
  • 8
  • Can you please provide a minimum reproducible example? – Raad Dec 13 '15 at 15:32
  • Your code is not reproducible. You didn't add `data.table` tag which would be worth to add. Read [How to make a great R reproducible example?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Don't expect to get quality answer, if any. – jangorecki Dec 13 '15 at 15:33
  • question is not clear. Can you please elaborate what you want to achieve. – cryptomanic Dec 13 '15 at 15:33

1 Answers1

1

Without an example this remains untested but it would seem to be a simple matter to use get which is the standard way to deliver an object when you only have a character representation of its name:

game_stats[,paste0('l',x,'g_', stat):=
             rollapply( get(pts), list(-(1:x)), mean, fill=NA, align='right'), by=team]

This assumes that you know that paste0 expressions were tested as effective for constructing names for assignment within :=.data.table .... which is a bit of a surprise to my reading, but that is what is implied by the preceding two lines. (Yes. It works for me, too.)

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Perfect, worked an absolute treat! Really appreciate you taking the time to think about the question even though there was no data, hopefully other people can learn from you in this regard as well. Many thanks – David Dec 13 '15 at 19:49