Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R : How to get a single element in data.table

Tags:

r

data.table

I want to get the first element from data.table

library(data.table)
dt <- data.table(data.frame(prices=c(1.1,2.4,5.3),
                            dates = c(2011-01-04,2011-01-05,2011-01-03)))
dt
     date       value
 1: 2011-01-04   1.1
 2: 2011-01-05   2.4
 3: 2011-01-03   5.3
> dt[1,1]
[1] 1
> dt[1]
     date       value
 1: 2011-01-04   1.1
> dt[1][1]
     date       value
 1: 2011-01-04   1.1

I need to get the first date. I'm not sure what i'm missing here :(

Thanks a lot. I was bit confused with the output.

dt[1, date]
[1] 2011-01-04
Levels: 2011-01-03 2011-01-04 2011-01-05 (any idea what levels mean?)

This also works st$date[1]. Implementation is same as data frame.

like image 965
on_the_shores_of_linux_sea Avatar asked Oct 20 '22 14:10

on_the_shores_of_linux_sea


1 Answers

Perhaps:

dt[1, date]

One of the joys of using data.table's is that the expressions in the 'j' position get evaluated in the context of the existing named columns. No need to use with().

like image 66
IRTFM Avatar answered Oct 24 '22 00:10

IRTFM