Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting the row of a data.table to a vector

Tags:

r

data.table

I want to turn data.table rows into vectors. Here's what worked for me:

unlist(dt[row_num])

But is there a more native solution? I also don't like that the above retains the name when really I want a pure numeric vector instead, which then leads to:

as.numeric(unlist(dt[row_num]))

Seems like there should be a better option.

like image 720
sunny Avatar asked Oct 29 '15 20:10

sunny


2 Answers

Ok, now I know you want a row:

as.matrix(dt[row_num])[1,]

IMO it is better to use first the data.table-operation and not to convert the complete datatable to a matrix. Simply the performance is better (especially on very large data.tables). Example:

library("data.table")
Iris <- data.table(iris[-5])
as.matrix(Iris[42])[1,]
like image 132
jogo Avatar answered Oct 12 '22 12:10

jogo


The problem with extracting rows as vectors is that vectors are homogeneous while rows of data frames or data tables are not.

However, you can convert the data to a matrix then extract the row:

> x <- iris[1:10,1:4]
> as.matrix(x)[1,]
Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
         5.1          3.5          1.4          0.2 
like image 45
Matthew Lundberg Avatar answered Oct 12 '22 12:10

Matthew Lundberg