Note that there are some explanatory texts on larger screens.

plurals
  1. POReferring to data.table columns by names saved in variables
    text
    copied!<p><code>data.table</code> is a fantastic R package and I am using it in a library I am developing. So far all is going very well, except for one complication. It seems to be much more difficult (compared to the conventional data frames) to refer to <code>data.table</code> columns using names saved in variables (as for data frames would be, for example: <code>colname="col"; df[df[,colname]&lt;5,colname]=0</code>). </p> <p>Perhaps what complicates the things most is the apparent lack of consistency of syntax on this in <code>data.table</code>. In some cases, <code>eval(colname)</code> and <code>get(colname)</code>, or even <code>c(colname)</code> seem to work. In others, <code>DT[,colname, with=F]</code> is the solution. Yet in others, such as, for example, the <code>set()</code> and <code>subset()</code> functions, I haven't found a solution at all. Finally, an extreme, albeit also quite common use case was discussed earlier (<a href="https://stackoverflow.com/questions/15009669/passing-column-names-to-data-table-programmatically">passing column names to data.table programmatically</a>) and the proposed solutions, albeit apparently doing their job, did not seem particularly readable... </p> <p>Perhaps I am complicating things too much? If anyone could jot down a quick cheatsheet for referring to <code>data.table</code> column names using variables for different common scenarios, I would be very grateful. </p> <p><strong>UPDATE:</strong></p> <p>Some specific examples that work provided I can hard code column names:</p> <pre><code>x.short = subset(x, abs(dist)&lt;=100) set(x, which(x$val&lt;10), "val", 0) </code></pre> <p>Now assume <code>distcol="dist"</code>, <code>valcol="val"</code>. What is the best way to do the above using <code>distcol</code> and <code>valcol</code>, but not <code>dist</code> and <code>val</code>?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload