rdata.table

Converting the row of a data.table to a vector


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.


Solution

  • 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