为什么不设置DT在这种情况下有任何效果? [英] Why doesn't setDT have any effect in this case?

查看:111
本文介绍了为什么不设置DT在这种情况下有任何效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码

library(data.table) # 1.9.2
x <- data.frame(letters[1:2]) 
setDT(x) 
class(x)
## [1] "data.table" "data.frame"

这是一个预期的结果。现在如果我运行

Which is an expected result. Now if I run

x <- letters[1:2]
setDT(data.frame(x)) 
class(x) 
## [1] "character"

类的 x 由于某种原因保持不变。

The class of x remained unchanged for some reason.

一种可能性是 setDT 只更改全局环境中的对象类,所以我尝试了

One possibility is that setDT changes only the classes of objects in the global environment, so I've tried

x <- data.frame(letters[1:2]) 
ftest <- function(x) setDT(x) 
ftest(x) 
class(x) 
##[1] "data.table" "data.frame"


$ b b

似乎 setDT 不太在意对象的环境以更改其类。

Seems like setDT don't care much about the environment of an object in order to change its class.

那么是什么导致了上述行为?是

So what's causing the above behaviour? Is it just a bug or there is some common sense behind it?

推荐答案

setDT 更改 data.frame ,并以不可见的方式返回。由于您不保存此 data.frame ,它会丢失。所有你需要做的是保存 data.frame ,以便 data.table 也被保存。例如。

setDT changes the data.frame and returns it invisibly. Since you don't save this data.frame, it is lost. All you need to do is somehow save the data.frame, so that the data.table is also saved. E.g.

setDT(y <- data.frame(x)) 
class(y)
## [1] "data.table" "data.frame"

z <- setDT(data.frame(x))
class(z)
## [1] "data.table" "data.frame"

这篇关于为什么不设置DT在这种情况下有任何效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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