我主要使用中的表格tibble格式来自tidyverse
,但对于某些步骤,我使用data.table
包裹。我想看看转换的最佳方法是什么数据表回到tibble?
我明白那个data.table
有一些巧妙的功能setDT https://rdrr.io/rforge/data.table/man/setDT.html and setDF https://rdrr.io/rforge/data.table/man/setDF.html函数,转换自数据框 to 数据表(反之亦然)通过引用,即不复制。
但如果我想转换回tibble?我是否使用复制数据as_tibble
on the 数据框产生于setDT()
?有没有一种聪明的方法来使用它,也许使用setattr()
from data.table
?
library(data.table)
library(tidyverse)
iris_tib <- as_tibble(iris)
## some data.table operation
setDT(iris_tib)
setkey(iris_tib, Species)
iris_tib[, Sepal.Length.Mean := mean(Sepal.Length), by = Species]
## How to convert back to tibble efficiently?
setDF(iris_tib)
iris_tib_back <- as_tibble(iris_tib)
## it looks like we were able to update by reference? Only rownames were (shallow) copied?
changes(iris_tib, iris_tib_back)
正如@Frank 提到的,这在一篇文章中进行了讨论here https://github.com/Rdatatable/data.table/issues/1877#issuecomment-253864899。一种可能性是使用setattr()
函数,设置属性引用。恰恰:
setattr(x, "class", c("tbl", "tbl_df", "data.frame"))
如果对原始类有疑问:
old_class <- class(iris_tib)
setDT(iris_tib)
.... # bunch of data.table operatios
setDF(iris_tib)
setattr(iris_tib, "class", old_class)
This seems完成转换回小标题的必要工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)