Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

r - Extract a column from a data.table as a vector, by position

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...