Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert data.table to data.frame (i.e. undo setDT)

I have a 20x2 dataframe. I converted that dataframe to a data.table to perform some operations (deleted the explanation of the operations and goal as out of scope). The conversion allowed me to avoid using a for loop. But the conversion generates some issues down the line.

I need to convert the df data.table back into a data.frame. How can I do that?

Thanks very much for your help.

df <- data.frame(LastPrice = c( 1221, 1220, 1220, 1217, 1216,  1218 , 1216, 1216, 1217, 1220, 1219, 1218, 1220, 1216, 1217, 1218, 1218, 1207, 1206, 1205), KCT = c( 1218, 1218, 1219, 1218, 1221,  1217 , 1217, 1216, 1219, 1216, 1217, 1216, 1219, 1217, 1218, 1217, 1217, 1217, 1219, 1217))

library(data.table)
setDT(df)
df[, check := as.integer(LastPrice > KCT)]
df[, Signal := do.call(pmin, shift(check, 0:2, type="lead"))]
like image 558
Krug Avatar asked Dec 25 '22 06:12

Krug


1 Answers

Just like setDT() converts its input to a data table by reference, there is also setDF() which converts its input to a data frame by reference. So just call

setDF(df)

and you are back to a data frame with no copies made.

like image 79
Rich Scriven Avatar answered Dec 26 '22 21:12

Rich Scriven