4

I have a data.table my.data.table and a character vector i (length one) corresponding a to a colname of my.data.table. Using i, I would like to extract the corresponding column of my.data.table as a vector that is not of class data.table or data.frame.

How would I do this?

> my.data.table <- data.table(a=1:2,b=2:3)
> i <- "a"
> class(my.data.table[,i,with=FALSE])
[1] "data.table" "data.frame"
> as.vector(my.data.table[,i,with=FALSE])  ##does not work
   a
1: 1
2: 2
> is.vector(as.vector(my.data.table[,i,with=FALSE])) ##strange behavior
[1] FALSE
> 

I assume there's a way to do this using with=FALSE and eval(i, <env>) in j but I can't figure it out.

Michael
  • 5,808
  • 4
  • 30
  • 39
  • @Marius is correct for a single column. `is.vector` returns TRUE if x is a vector of the specified mode having no attributes other than names. It returns FALSE otherwise. Both data.tables and data.frames are lists, and therefore vectors with many attributes – mnel Dec 10 '12 at 23:55
  • See [here](http://stackoverflow.com/questions/1169456/in-r-what-is-the-difference-between-the-and-notations-for-accessing-the) for an explanation- once you've got a hang on the difference between `[` and `[[` these issues become much easier to deal with. – Marius Dec 10 '12 at 23:58

1 Answers1

6

Either one of these will work in your example, but the second of the two is more generally useful.

my.data.table[[i]]
# [1] 1 2
my.data.table[,..i][[1L]]
# [1] 1 2

.. in data.table means to "look up one level" (in this case for the variable i)

MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • What's nice about the second statement is that it also works if the rows have to be subset as well: `my.data.table[2, i, with=FALSE][[1]]`. I am still waiting for `drop=TRUE` to be implemented, though. – Christian David Aug 12 '14 at 11:20