选择data.table的列并返回向量 [英] Select column of data.table and return vector
问题描述
是否可以选择data.table的列并返回向量?在基数R中,参数 drop = TRUE
可以解决问题。例如,
Is it possible to select a column of a data.table and get back a vector? In base R, the argument drop=TRUE
would do the trick. For example,
library(data.table)
dat <- as.data.table(iris)
dat[,"Species"] # returns data.table
dat[,"Species", drop=TRUE] # same
iris[, "Species", drop=TRUE] # a factor, wanted result
是否可以使用 data.table
?
编辑:dat [,Species]方法很好,但是我需要一种可以在变量中传递列名的方法:
the dat[,Species] method is fine, however I need a method where I can pass the column name in a variable:
x <- "Species"
dat[,x, drop=TRUE]
推荐答案
带有 data.frame
,默认值为 drop = TRUE
,在 data.table
中,它在内部完成时相反。根据?data.table
With data.frame
, the default is drop = TRUE
and in data.table
, it is the opposite while it is done internally. According to ?data.table
drop-从未被data.table使用。不使用。它必须在这里,因为data.table继承自data.frame。
drop - Never used by data.table. Do not use. It needs to be here because data.table inherits from data.frame.
为了获得相同的行为,我们可以使用 [[通过传递字符串来提取列
In order to get the same behavior, we can use [[
to extract the column by passing a string
identical(dat[["Species"]], iris[, "Species"])
#[1] TRUE
或
dat$Species
通过使用 [[[
或 $
,它提取为 vector
,同时绕过 data.table
开销
By using [[
or $
, it extracts as a vector
while also bypass the data.table
overhead
这篇关于选择data.table的列并返回向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!