20

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.

3
  • 9
    that is the native solution for converting a list to vector in R; also note the use.names argument of unlist
    – eddi
    Commented Oct 29, 2015 at 20:28
  • 1
    You can also remove names with unname. Commented Oct 29, 2015 at 20:42
  • 3
    I agree with BondedDust's first sentence here: stackoverflow.com/a/8595099/1191259 "Technically lists are vectors, although very few would use that term." In that sense, you can stop at c(dt[row_num])
    – Frank
    Commented Oct 29, 2015 at 21:05

3 Answers 3

17

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,]
0
16

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 
1

Use melt.data.table(), by specifying the row, along with the columns you want to extract (use measure.vars = 1:ncol(iris.dt) for the whole row). Select the values by adding [, value] on the end. It's best to specify columns that are all of the same type, or all the values will be converted to character (with a warning).

library("data.table")
iris.dt <- data.table(iris)

# One line solution:
row1 <- melt.data.table(iris.dt[1], measure.vars = 1:4)[, value]

# In steps:
iris.row1 <- iris.dt[1]
#    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1:          5.1         3.5          1.4         0.2  setosa

iris.melted <- melt.data.table(iris.row1, measure.vars = 1:4)
# variable  value
# 1: Sepal.Length    5.1
# 2:  Sepal.Width    3.5
# 3: Petal.Length    1.4
# 4:  Petal.Width    0.2

row1 <- iris.melted[, value]
# [1] "5.1"    "3.5"    "1.4"    "0.2"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.