newbie
newbie

Reputation: 907

Extract data.table as vector in case of many columns

supposed we have

dt <- data.table(x = 5, y = 4, z = 6)

If we want the return to be a vector,[1] 5 4 6, we use dt[,c(x, y, z)].

How should I write the code if there are many columns?

Upvotes: 0

Views: 74

Answers (2)

Colonel Beauvel
Colonel Beauvel

Reputation: 31181

If you want to return the first row as vector, you can simply do:

unlist(dt[1,])
#x y z 
#5 4 6 

Upvotes: 2

Jaap
Jaap

Reputation: 83275

If you want to return a vector of the columnnames, you can use the following options:

names(dt)

or

colnames(dt)

or

dt[,names(dt)]

If you want to return the first row, you can just use:

unlist(dt[1])

Upvotes: 3

Related Questions