2014-05-10 18 views
17

Stavo giocando con data.table e mi sono imbattuto in una distinzione che non sono sicuro di capire. Dato il seguente set di dati:Comprensione .I in data.table in R

library(data.table) 

set.seed(400) 
DT <- data.table(x = sample(LETTERS[1:5], 20, TRUE), key = "x"); DT 

Si può spiegare a me la differenza tra le seguenti espressioni?

1) DT[J("E"), .I]

2) DT[ , .I[x == "E"] ]

3) DT[x == "E", .I]

risposta

23
set.seed(400) 
library(data.table) 

DT <- data.table(x = sample(LETTERS[1:5], 20, TRUE), key = "x"); DT 

1)

DT[ , .I[x == "E"] ] # [1] 18 19 20 

è un data.table dove .I è un vettore che rappresenta la riga numero di E nell'insieme di dati ORIGINALE DT

2)

DT[J("E") , .I] # [1] 1 2 3 

DT["E"  , .I] # [1] 1 2 3 

DT[x == "E", .I] # [1] 1 2 3 

sono tutti uguali, producendo un vettore in cui .I s sono vettori che rappresentano i numeri di riga dei E s nel nuovo subsetted dati