Retrieving a column from a data table. As a position vector

How to extract a column from data.table as a vector by its position? Below are some snippets of code I tried:

DT<-data.table(x=c(1,2),y=c(3,4),z=c(5,6)) DT # xyz #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 

Another way to get this output using a column position

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

It does not give a vector

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

These two do not 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 does not 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 
+58
vector r indexing data.table
Nov 18 '13 at 8:37
source share
2 answers

Data.table inherits from the data.frame class. Therefore, it is an internal element of list (column vectors) and can be considered as such.

 is.list(DT) #[1] TRUE 

Fortunately, a subset of the list, i.e. [[ , very fast and, unlike [ , package data.table does not define a method for it. That way you can just use [[ to retrieve by index:

 DT[[2]] #[1] 3 4 
+76
Nov 18 '13 at 8:43
source share

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

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

+3
Jun 03 '18 at 3:07 on
source share



All Articles