0

I need to extract a column from a data.table in the form of a vector. I understand that $ works and [] doesn't. Nevertheless, as.vector() fails on a data.table object of a single dimension.

    library(data.table)
    dt <- iris
    setDT(dt)
    oneCol1 <- dt$Sepal.Length[1:100] # produces a vector of 100 elements, fine
    oneCol2 <- dt[1:100,1] # produces a DT 100 rows by 1 column. I understand limitation.
    v <- as.vector(oneCol2) 
    is.vector(v) # FALSE

The documentation says as.vector()"attempts to coerce ... x, an R object." Nothing happens, though. v remains a DT object.

Sure, I can can use the first method, but I wonder why as.vector() doesn't work.

Robert Hadow
  • 457
  • 4
  • 15
  • You are basically telling R to convert a data table / data frame into a vector. how is that supposed to work and what is wrong with just doing `v <- as.vector(oneCol2$Sepal.Length)`? – tifu Jul 09 '18 at 12:33
  • you need `unlist` – Cath Jul 09 '18 at 12:34
  • "I need to extract a column" -- `dt[[1]][1:100]`? You can also type `vignette("datatable-faq")` and read the first answer. (I'd suggest reading the whole thing.) – Frank Jul 09 '18 at 12:47

1 Answers1

1

Data frames are lists. Even if you select one row of a data, it's still considered as a list.

use unlist instead :

 library(data.table)
dt <- iris
setDT(dt)
oneCol1 <- dt$Sepal.Length[1:100] # produces a vector of 100 elements, fine
oneCol2 <- dt[1:100,1] # produces a DT 100 rows by 1 column. I understand limitation.
t<-unlist(oneCol2)
is.vector(t) # true