1

Using the ":" operator I'm trying to add columns in j argument in data table. These are simple 6 months and 12 Months .. 36 months aggregations

OrderQty36M[,':='(Stat6M=sum(M14:M19)),(Stat12M=sum(M14:M25))]

Can the ":" argument be used as a sequence operator in data table or there is some other way?

in [.data.table(OrderQty36M, , :=(Stat6M = sum(M14:M19)), (Stat12M = sum(M14:M25))) :
The items in the 'by' or 'keyby' list are length (1). Each must be same length as rows in x or number of rows returned by i (36703).
In addition: Warning messages:
1: In M14:M25 :
numerical expression has 36703 elements: only the first used
2: In M14:M25 :
numerical expression has 36703 elements: only the first used

  • 1
    Possible duplicate of 1. [When should I use the := operator in data.table?](https://stackoverflow.com/questions/7029944/when-should-i-use-the-operator-in-data-table) 2. [What is the R assignment operator := for?](https://stackoverflow.com/questions/32817780/what-is-the-r-assignment-operator-for) 3. [colons equals operator in R? new syntax?](https://stackoverflow.com/questions/32077483/colons-equals-operator-in-r-new-syntax) 4. [Why is := allowed as an infix operator?](https://stackoverflow.com/questions/26269423/why-is-allowed-as-an-infix-operator) – M-- Jul 13 '19 at 21:04
  • Possible duplicate of [When should I use the := operator in data.table?](https://stackoverflow.com/questions/7029944/when-should-i-use-the-operator-in-data-table) – M-- Jul 13 '19 at 21:06

1 Answers1

0

There are a few things confused in how you are trying to use data.table here:

  1. Your calculation for Stats12M is in the by column which I don't believe is intended. The brackets from the Stats6M calculation should be extended around the Stats12M calculation.
  2. I don't think that data.table can select columns with the syntax M14:M19. Fortunately, dplyr can using the select function.
  3. I think you are intending to sum across rows rather than the columns so you want to use rowSums rather than sum.

My corrected version of the code is below.

OrderQty36M[,':='(Stat6M=rowSums(select(.SD,M14:M19)), Stat12M=rowSums(select(.SD,M14:M25)))][]
D. Stevens
  • 73
  • 4