3

How can I access just a single cell in a data.table in the way as I could for a data.frame:

mdf <- data.frame(a = c("A", "B", "C"), b = rnorm(3), c = 1:3)
mdf[ mdf$a == "B", "c" ]
[1] 2

Doing the analogue on a data.table a data.table is returned including the key column(s):

mdt <- data.table( mdf, key = "a" )
mdt[ "B", c ]
   a c
1: B 2

mdt[ "B", c ][ , c]
[1] 2

Did I miss a parameter or does it has to be done as in the last line?

4

2 回答 2

0

Recent versions of data.table make this easier

mdt[ "B", c]
# [1] 2

Original answer was returning a data.table like:

mdt['B', 'c']
#        c
# 1:     2
于 2013-05-21T10:19:48.347 回答
0

Either of these will avoid repeating the c but are not as efficient since they involve computing the first [] as well as the final answer:

> mdt[ "B", ][["c"]]
[1] 2
> mdt[ "B", ][, c]
[1] 2
于 2013-05-21T12:36:41.123 回答