Should a variable be called twice before evaluating?

Something really strange is happening here. In the code below, I create a variable called temp . I have to call him twice before I can understand what it is. For instance. The first time I call it, the console shows nothing. The second time, it shows data.table / data.frame what it is. Can someone help me understand what is going on here?

 library(magrittr) library(data.table) myDT <- as.data.table(mtcars) temp <- myDT %>% melt(id.vars = c('cyl', 'mpg', 'hp'), measure.vars = c('vs','am','gear','carb'), variable.name = 'Data') %>% extract( value > 0) %>% extract( , value := NULL) 

What does my console do (the first call does nothing):

 > temp > temp cyl mpg hp Data 1: 4 22.8 93 vs 2: 6 21.4 110 vs 3: 6 18.1 105 vs 4: 4 24.4 62 vs 5: 4 22.8 95 vs ... ... 
+6
source share
1 answer

This is a well-known side effect of the fix, implemented for squash is an even bigger bug. He documented here as the first item in the "BUG FIXES" section of version v1.9.6. Quote from this link:

if (TRUE) DT [, LHS: = RHS] no longer prints, # 869 and # 1122. Added tests. For this to work, we had to live with one drawback: if a: = is used inside the function without DT [] until the end of the function, then the next time DT or print (DT) is entered at the prompt, nothing will be printed. Repeated DT or print (DT) will be printed. To avoid this: include DT [] after the last: = in your function. If this is not possible (for example, this is not a function that you can change), then DT [] in the prompt will be guaranteed to print. As before, adding an extra [] at the end of the request: = is the recommended idiom for updating and then printing; for example> DT [, foo: = 3L] []. Thanks to Yuryus and Jan Gorecki for the message.

As explained here, the solution is to add the final [] to the final operation := in your function. Here it will mean the following:

 library(magrittr) library(data.table) myDT <- as.data.table(mtcars) temp <- myDT %>% melt(id.vars = c('cyl', 'mpg', 'hp'), measure.vars = c('vs','am','gear','carb'), variable.name = 'Data') %>% extract( value > 0) %>% extract( , value := NULL) %>% `[` ## Following which, this will print the first time temp 
+9
source

All Articles