EVOLUTION-MANAGER
Edit File: setkey.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>R: Create key on a data.table</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="R.css" /> </head><body> <table width="100%" summary="page for setkey {data.table}"><tr><td>setkey {data.table}</td><td style="text-align: right;">R Documentation</td></tr></table> <h2> Create key on a data.table </h2> <h3>Description</h3> <p><code>setkey</code> sorts a <code>data.table</code> and marks it as sorted with an attribute <code>sorted</code>. The sorted columns are the key. The key can be any number of columns. The columns are always sorted in <em>ascending</em> order. The table is changed <em>by reference</em> and <code>setkey</code> is very memory efficient. </p> <p>There are three reasons <code>setkey</code> is desirable: i) binary search and joins are faster when they detect they can use an existing key, ii) grouping by a leading subset of the key columns is faster because the groups are already gathered contiguously in RAM, iii) simpler shorter syntax; e.g. <code>DT["id",]</code> finds the group "id" in the first column of DT's key using binary search. It may be helpful to think of a key as super-charged rownames: multi-column and multi-type rownames. </p> <p>In <code>data.table</code> parlance, all <code>set*</code> functions change their input <em>by reference</em>. That is, no copy is made at all other than for temporary working memory, which is as large as one column. The only other <code>data.table</code> operator that modifies input by reference is <code><a href="assign.html">:=</a></code>. Check out the <code>See Also</code> section below for other <code>set*</code> functions <code>data.table</code> provides. </p> <p><code>setindex</code> creates an index for the provided columns. This index is simply an ordering vector of the dataset's rows according to the provided columns. This order vector is stored as an attribute of the <code>data.table</code> and the dataset retains the original order of rows in memory. See the <a href="../doc/datatable-secondary-indices-and-auto-indexing.html"><code>vignette("datatable-secondary-indices-and-auto-indexing")</code></a> for more details. </p> <p><code>key</code> returns the <code>data.table</code>'s key if it exists; <code>NULL</code> if none exists. </p> <p><code>haskey</code> returns <code>TRUE</code>/<code>FALSE</code> if the <code>data.table</code> has a key. </p> <h3>Usage</h3> <pre> setkey(x, ..., verbose=getOption("datatable.verbose"), physical = TRUE) setkeyv(x, cols, verbose=getOption("datatable.verbose"), physical = TRUE) setindex(...) setindexv(x, cols, verbose=getOption("datatable.verbose")) key(x) indices(x, vectors = FALSE) haskey(x) </pre> <h3>Arguments</h3> <table summary="R argblock"> <tr valign="top"><td><code>x</code></td> <td> <p> A <code>data.table</code>. </p> </td></tr> <tr valign="top"><td><code>...</code></td> <td> <p> The columns to sort by. Do not quote the column names. If <code>...</code> is missing (i.e. <code>setkey(DT)</code>), all the columns are used. <code>NULL</code> removes the key. </p> </td></tr> <tr valign="top"><td><code>cols</code></td> <td> <p> A character vector of column names. For <code>setindexv</code>, this can be a <code>list</code> of character vectors, in which case each element will be applied as an index in turn. </p> </td></tr> <tr valign="top"><td><code>verbose</code></td> <td> <p> Output status and information. </p> </td></tr> <tr valign="top"><td><code>physical</code></td> <td> <p><code>TRUE</code> changes the order of the data in RAM. <code>FALSE</code> adds an index. </p> </td></tr> <tr valign="top"><td><code>vectors</code></td> <td> <p><code>logical</code> scalar, default <code>FALSE</code>; when set to <code>TRUE</code>, a <code>list</code> of character vectors is returned, each referring to one index. </p> </td></tr> </table> <h3>Details</h3> <p><code>setkey</code> reorders (i.e. sorts) the rows of a <code>data.table</code> by the columns provided. The sort method used has developed over the years and we have contributed to base R too; see <code><a href="../../base/html/sort.html">sort</a></code>. Generally speaking we avoid any type of comparison sort (other than insert sort for very small input) preferring instead counting sort and forwards radix. We also avoid hash tables. </p> <p>Note that <code>setkey</code> always uses "C-locale"; see the Details in the help for <code><a href="setorder.html">setorder</a></code> for more on why. </p> <p>The sort is <em>stable</em>; i.e., the order of ties (if any) is preserved. </p> <p>For character vectors, <code>data.table</code> takes advantage of R's internal global string cache, also exported as <code><a href="chmatch.html">chorder</a></code>. </p> <h3>Value</h3> <p>The input is modified by reference and returned (invisibly) so it can be used in compound statements; e.g., <code>setkey(DT,a)[.("foo")]</code>. If you require a copy, take a copy first (using <code>DT2=copy(DT)</code>). <code><a href="copy.html">copy</a></code> may also sometimes be useful before <code>:=</code> is used to subassign to a column by reference. </p> <h3>Good practice</h3> <p>In general, it's good practice to use column names rather than numbers. This is why <code>setkey</code> and <code>setkeyv</code> only accept column names. If you use column numbers then bugs (possibly silent) can more easily creep into your code as time progresses if changes are made elsewhere in your code; e.g., if you add, remove or reorder columns in a few months time, a <code>setkey</code> by column number will then refer to a different column, possibly returning incorrect results with no warning. (A similar concept exists in SQL, where <code>"select * from ..."</code> is considered poor programming style when a robust, maintainable system is required.) </p> <p>If you really wish to use column numbers, it is possible but deliberately a little harder; e.g., <code>setkeyv(DT,names(DT)[1:2])</code>. </p> <p>If you wanted to use <code><a href="../../base/html/grep.html">grep</a></code> to select key columns according to a pattern, note that you can just set <code>value = TRUE</code> to return a character vector instead of the default integer indices. </p> <h3>References</h3> <p><a href="https://en.wikipedia.org/wiki/Radix_sort">https://en.wikipedia.org/wiki/Radix_sort</a><br /> <a href="https://en.wikipedia.org/wiki/Counting_sort">https://en.wikipedia.org/wiki/Counting_sort</a><br /> <a href="http://stereopsis.com/radix.html">http://stereopsis.com/radix.html</a><br /> <a href="https://codercorner.com/RadixSortRevisited.htm">https://codercorner.com/RadixSortRevisited.htm</a><br /> <a href="https://cran.r-project.org/package=bit64">https://cran.r-project.org/package=bit64</a><br /> <a href="https://github.com/Rdatatable/data.table/wiki/Presentations">https://github.com/Rdatatable/data.table/wiki/Presentations</a> </p> <h3>See Also</h3> <p><code><a href="data.table.html">data.table</a></code>, <code><a href="tables.html">tables</a></code>, <code><a href="J.html">J</a></code>, <code><a href="../../base/html/order.html">sort.list</a></code>, <code><a href="copy.html">copy</a></code>, <code><a href="setDT.html">setDT</a></code>, <code><a href="setDF.html">setDF</a></code>, <code><a href="assign.html">set</a></code> <code><a href="assign.html">:=</a></code>, <code><a href="setorder.html">setorder</a></code>, <code><a href="setcolorder.html">setcolorder</a></code>, <code><a href="setattr.html">setattr</a></code>, <code><a href="setattr.html">setnames</a></code>, <code><a href="chmatch.html">chorder</a></code>, <code><a href="setNumericRounding.html">setNumericRounding</a></code> </p> <h3>Examples</h3> <pre> # Type 'example(setkey)' to run these at the prompt and browse output DT = data.table(A=5:1,B=letters[5:1]) DT # before setkey(DT,B) # re-orders table and marks it sorted. DT # after tables() # KEY column reports the key'd columns key(DT) keycols = c("A","B") setkeyv(DT,keycols) DT = data.table(A=5:1,B=letters[5:1]) DT2 = DT # does not copy setkey(DT2,B) # does not copy-on-write to DT2 identical(DT,DT2) # TRUE. DT and DT2 are two names for the same keyed table DT = data.table(A=5:1,B=letters[5:1]) DT2 = copy(DT) # explicit copy() needed to copy a data.table setkey(DT2,B) # now just changes DT2 identical(DT,DT2) # FALSE. DT and DT2 are now different tables DT = data.table(A=5:1,B=letters[5:1]) setindex(DT) # set indices setindex(DT, A) setindex(DT, B) indices(DT) # get indices single vector indices(DT, vectors = TRUE) # get indices list </pre> <hr /><div style="text-align: center;">[Package <em>data.table</em> version 1.14.4 <a href="00Index.html">Index</a>]</div> </body></html>