@@ -39,6 +39,20 @@ ordering vector of the dataset's rows according to the provided columns. This or
3939is stored as an attribute of the \code {data.table } and the dataset retains the original order
4040of rows in memory. See the \href {.. / doc / datatable - secondary - indices - and - auto - indexing.html }{\code {vignette(" datatable-secondary-indices-and-auto-indexing" )}} for more details.
4141
42+ \subsection {Key vs. Index Subsetting }{
43+ When using \code {setkey }:
44+ \itemize {
45+ \item Subsetting can omit \code {on } (e.g. , \code {DT [.(value )]})
46+ \item Data is physically reordered in RAM
47+ }
48+ When using \code {setindex }:
49+ \itemize {
50+ \item Must specify \code {on } (e.g. , \code {DT [.(value ), on = " col" ]})
51+ \item Multiple indices can coexist via \code {setindexv(x , list (cols ))}
52+ \item Original row order is preserved
53+ }
54+ }
55+
4256\code {key } returns the \code {data.table }' s key if it exists; \c ode{NULL} if none exists.
4357
4458\c ode{haskey} returns \c ode{TRUE}/\c ode{FALSE} if the \c ode{data.table} has a key.
@@ -142,6 +156,15 @@ setindex(DT, B)
142156indices(DT ) # get indices single vector
143157indices(DT , vectors = TRUE ) # get indices list
144158
159+ # Keyed subsetting (no 'on' needed)
160+ setkey(DT , B )
161+ DT [.(" e" )] # Returns row where B = "e"
162+
163+ # Indexed subsetting (requires 'on')
164+ setindex(DT , B )
165+ DT [.(" e" ), on = " B" ] # Works
166+ # DT[.("e")] # Would error (missing 'on')
167+
145168# Setting multiple indices at once
146169DT = data.table(A = 5 : 1 , B = letters [5 : 1 ], C = 10 : 6 )
147170setindexv(DT , list (c(" A" , " B" ), c(" B" , " C" )))
0 commit comments