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

如何根据列的位置从 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
83722 次浏览

A data.table inherits from class data.frame. Therefore it is a list (of column vectors) internally and can be treated as such.

is.list(DT)
#[1] TRUE

Fortunately, list subsetting, i.e. [[, is very fast and, in contrast to [, package data.table doesn't define a method for it. Thus, you can simply use [[ to extract by an index:

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

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

where colNb can be an integer (the desired column number) or a variable containing the column number.