R data.table:如何从小标题到data.table再到小标题? [英] R data.table: how to go from tibble to data.table to tibble back?

查看:66
本文介绍了R data.table:如何从小标题到data.table再到小标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要使用 tidyverse 中atat的 tibble 中的表,但是对于某些步骤,我使用了 data.table 包.我想看看将 data.table 转换回 tibble 的最佳方法是什么?

I use mainly tables in the tibble fromat from tidyverse, but for some steps, I use the data.table package. I want to see what is the best way of converting a data.table back to tibble?

我了解 data.table 具有一些巧妙的功能 setDT setDF 函数,它们从 data.frame data.table (反之亦然),即不进行复制.

I understand that data.table has some clever function setDT and setDF function, that convert from data.frame to data.table (and vice-versa) by reference, i.e. without making a copy.

但是如果我想转换回 tibble 怎么办?我是否使用 setDT()生成的 data.frame 上的 as_tibble 复制数据?是否有一个聪明的方法可以使用此方法,也许使用 data.table 中的 setattr()?

But what if I wanted to convert back to tibble? Am I copying the data using as_tibble on the data.frame resulting from setDT()? Is there a clever way to use this, maybe using the 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所述,这在帖子

As @Frank mentioned, this was discussed in a post here. One possibility is to use the setattr() function, which set attributes by reference. Precisely:

setattr(x, "class", c("tbl", "tbl_df", "data.frame"))

如果对原始课程有疑问:

And if there's a doubt about the original class:

old_class <- class(iris_tib)
setDT(iris_tib)
.... # bunch of data.table operatios
setDF(iris_tib)
setattr(iris_tib, "class", old_class)

似乎可以完成将其转换回小标题的必要工作.

This seems to do the necessary job converting back to a tibble.

这篇关于R data.table:如何从小标题到data.table再到小标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆