0 votes
1 view
in R Programming by (5.3k points)

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

Another 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

1 Answer

0 votes
by (25.3k points)

A data.table is a list (of column vectors) internally so, therefore, it can be treated as such.i.e.,

 

is.list(DT)

 #[1] TRUE

Thus, you can simply use [[ to extract by an index:

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[[2]]

[1] 3 4

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...