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

寵の児 提交于 2020-01-30 05:24:52

问题


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"))]

回答1:


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.



来源:https://stackoverflow.com/questions/36671531/convert-data-table-to-data-frame-i-e-undo-setdt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!