通过位置从数据表中提取列作为向量 [英] Extract a column from a data.table as a vector, by position
问题描述
如何从数据表中提取列作为向量的位置?下面是我试过的一些代码片段:
DT <-data.table(x = c = c(3,4),z = c(5,6))
DT
#xyz
#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 FALSE])
#[1] FALSE
p>
DT $ noquote(names(DT)[2])#无效
#Error:函数
DT [,noquote(names(DT)[2])]#不工作
#[1] y
这不会给出一个向量:
DT [,noquote(names(DT)[2]),with = FALSE]#不是向量
#y
#1:3
#2:4
。向量(DT [,noquote(names(DT)[2]),with = FALSE])
#[1] FALSE
解决方案 data.table继承自 data.frame
类。因此,它在内部是一个列表
(列向量),可以这样处理。
is.list(DT)
#[1] TRUE
幸运的是,列表子集,即 [[
c $ c> [
,package data.table没有为它定义一个方法。因此,您可以简单地使用 [[
以索引提取: DT [[2]]
#[1] 3 4
How do I extract a column from a data.table as a vector by its position? Below are some code snippets I have tried:
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
I want to get this output using column position
DT$y
#[1] 3 4
is.vector(DT$y)
#[1] TRUE
Other way to get this output using column position
DT[,y]
#[1] 3 4
is.vector(DT[,y])
#[1] TRUE
This doesn't give a vector
DT[,2,with=FALSE]
# y
#1: 3
#2: 4
is.vector(DT[,2,with=FALSE])
#[1] FALSE
Those two doesn't work:
DT$noquote(names(DT)[2]) # Doesn't work
#Error: attempt to apply non-function
DT[,noquote(names(DT)[2])] # Doesn't work
#[1] y
And this doesn't give a vector:
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
解决方案 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
这篇关于通过位置从数据表中提取列作为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!