3

So, I have been learning how to use data.table, I used the example on the ??dcast where is use the following example

dt = data.table(x=sample(5,20,TRUE), y=sample(2,20,TRUE), 
                z=sample(letters[1:2], 20,TRUE), d1 = runif(20), d2=1L) 

then

# multiple value.var
dcast(dt, x + y ~ z, fun=sum, value.var=c("d1","d2"))

and I get the error:

Error in .subset2(x, i, exact = exact) : subscript out of bounds In addition: Warning message: In if (!(value.var %in% names(data))) { :
the condition has length > 1 and only the first element will be used

here is the information of my R version:

> version
               _                           
platform       x86_64-w64-mingw32          
arch           x86_64                      
os             mingw32                     
system         x86_64, mingw32             
status                                     
major          3                           
minor          2.2                         
year           2015                        
month          08                          
day            14                          
svn rev        69053                       
language       R                           
version.string R version 3.2.2 (2015-08-14)
nickname       Fire Safety
Jaap
  • 81,064
  • 34
  • 182
  • 193
dpuleo
  • 313
  • 3
  • 10
  • 3
    Not able to reproduce the error with `R 3.2.3` and `data.table_1.9.6` – akrun Feb 12 '16 at 19:49
  • 4
    On R 3.2.3 with data.table 1.9.7, I see no error. Fyi, the multiple value.var feature was added in 1.9.6: https://github.com/Rdatatable/data.table – Frank Feb 12 '16 at 19:49

1 Answers1

9

I encountered this same thing and it was frustrating as heck.

The answer/problem is that you need to "force" the data.table dcast function otherwise it will use the reshape2 function

The only way I was successfull was running dcast as follows:

# multiple value.var
data.table::dcast(dt, x + y ~ z, fun=sum, value.var=c("d1","d2"))
K.J.J.K
  • 429
  • 5
  • 12
  • This can also be avoided by loading just the `data.table` library, or loading `data.table` before `reshape2`. This one is particularly annoying because it's only an issue if you've loaded `reshape2` *and then* `data.table`, meaning that it's often not an issue – Mako212 Jan 28 '19 at 18:56
  • This is also correct. Package loading order can cause many problems if functions mask other functions... Can be frustrating – K.J.J.K Feb 12 '19 at 13:59
  • I have loaded data.table first and then reshape2, but the issue persists, @K.J.J.K answer is my option until now. – Ricardo Andrade Sep 23 '21 at 23:22
  • @K.J.J.K you saved my life – isthisthat Jun 13 '23 at 13:45