88

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
3
  • For tablature data in general, you should check out dplyr ;)
    – Mullefa
    May 29, 2015 at 13:09
  • 27
    @Mullefa I don't see a reason why you felt the need for this comment.
    – Roland
    Jun 30, 2015 at 7:16
  • 2
    @Mullefa: data.table beats dplyr for some types of tablature data. It's the OP choice to use it.
    – smci
    Apr 29, 2017 at 11:51

2 Answers 2

114

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
2
  • Is it possible to maintain the data.table structure rather than convert to a vector? Does this for multiple columns? Jan 8, 2016 at 21:23
  • ...and if you wished to subset the data on a specific number of rows alongside a particular column (e.g. in this instance column 2) , you add an additional set of square brackets at the front of the query. That is, if you want the first 10 rows of column 2 then... DT[1:10][[2]] Thanks this has made my code much faster! Dec 5, 2019 at 16:57
4

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.