按位置从 data.table 中提取列作为向量

问题描述 投票:0回答:2

如何按位置从 data.table 中提取列作为向量?以下是我尝试过的一些代码片段:

DT<-data.table(x=c(1,2),y=c(3,4),z=c(5,6))
DT
#   x y z
#1: 1 3 5
#2: 2 4 6

我想使用列位置获得此输出

DT$y 
#[1] 3 4
is.vector(DT$y)
#[1] TRUE

使用列位置获取此输出的其他方法

DT[,y] 
#[1] 3 4
is.vector(DT[,y])
#[1] TRUE

这没有给出向量

DT[,2,with=FALSE]
#   y
#1: 3
#2: 4
is.vector(DT[,2,with=FALSE])
#[1] FALSE

这两个不起作用:

DT$noquote(names(DT)[2]) # Doesn't work
#Error: attempt to apply non-function

DT[,noquote(names(DT)[2])] # Doesn't work
#[1] y

这并没有给出向量:

DT[,noquote(names(DT)[2]),with=FALSE] # Not a vector
#   y
#1: 3
#2: 4
is.vector(DT[,noquote(names(DT)[2]),with=FALSE])
#[1] FALSE
r vector indexing data.table
2个回答
122
投票

data.table 继承自类

data.frame
。因此,它在内部是一个
list
(列向量),并且可以这样对待。

is.list(DT)
#[1] TRUE

幸运的是,从列表中提取向量(即

[[
)非常快,并且与
[
相比,包 data.table 没有为其定义方法。因此,您可以简单地使用
[[
通过索引提取:

DT[[2]]
#[1] 3 4

5
投票

DT[,get(names(DT)[colNb])]

其中 colNb 可以是整数(所需的列号)或包含列号的变量。

© www.soinside.com 2019 - 2024. All rights reserved.