为什么data.table设置为“ with” = F,当j是单列时输出data.table? [英] Why does data.table, setting "with" = F, output a data.table when j is a single column?

查看:83
本文介绍了为什么data.table设置为“ with” = F,当j是单列时输出data.table?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有数据表dt。

Let's say I have data table dt.

dt = as.data.table(c(0,1,2,3))

我想知道为什么dt的行为在以下两行代码中有所不同。

I'd like to know why the behavior of dt differs in the following two lines of code.

dt[,V1]

dt[,"V1",with=F]

具体来说,第一行生成数字矢量,而第二行生成data.table。

Specifically, the first line produces a numeric vector while the second line produces a data.table.

我想构建一个函数,该函数允许我通过传递字符串来动态检索单个列(因此使用= F),并将该输出用于某些其他函数。现在,后一种情况的行为可能会导致某些函数(例如ecdf和hist)出错,这些函数不接受data.frame或data.table。

I'd like to build a function that would allow me to retrieve single columns dynamically by passing a string (thus with=F) and use that output in certain other functions. As it is now, the behavior in the latter case can cause an error in some functions, such as ecdf and hist, which don't accept a data.frame or data.table.

这是我已经解决的方法。

Here's a workaround I've made.

as.data.frame(dt[,"V1",with=F])[,1]

这将返回预期的输出:一个与ecdf很好玩的向量和历史。有点混乱。是否有任何原因导致 dt [, V1,with = F] 中的行为不同于 dt [,V1]

This returns the expected output: a vector which plays nicely with ecdf and hist. It's just a bit messy. Is there any reason why the behavior in dt[,"V1",with=F] differs from dt[,V1]?

推荐答案

根据data.table 常见问题解答,许多data.frame用户在从data.frame返回单个列而未设置<$ c时遇到错误$ c> drop = FALSE 。这些用户希望使用单列data.frame输出,而不是矢量。当 with = FALSE 符合这些用户的期望时,data.table的默认行为。

According to the data.table FAQ, many users of data.frame experienced errors when they returned a single column from a data.frame without setting drop=FALSE. These users expected a single column data.frame output rather than a vector. The default behavior of data.table when with=FALSE conforms to these users' expectations.

这篇关于为什么data.table设置为“ with” = F,当j是单列时输出data.table?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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