Hi,<br><br>For some time I have been wishing that data.table and ggplot2 could play a bit nicer together.<br>For example, I would like this to work but it doesn't:<br><br>> test <- data.table(a=1:10, b=1:10)<br>> test[, ggplot() + geom_line(aes(x=a, y=b))]<br>
Error in eval(expr, envir, enclos) : object 'a' not found<br><br>I spent a few dozen minutes trying to understand what was going on (and stumbling upon <a href="http://stackoverflow.com/questions/3737619/how-can-i-pass-a-ggplot2-aesthetic-from-a-variable">this useful advice from Hadley Wickham</a>), and it turns out that it's very easy to fix (though the fix is not very pretty).<br>
Datatable-help, I present you with.. aesDT and ggplotDT.<br><br><br>aesDT <- function(...) {<br> aes <- structure(list(...), class = "uneval")<br> rename_aes(aes)<br>}<br><br>Using aesDT() instead of aes() whenever you are in a data.table (or in a with()) will now work. That is pretty much all you need, but I thought I'd go just one tiny step further with ggplotDT():<br>
<br>ggplotDT <- function(...) {<br> ggplot(, aes_now(...))<br>}<br><br>which makes the following possible:<br><br>test[, ggplotDT(x=a, y=b) + geom_line()]<br><br><div>i.e. put the aesthetics directly as arguments, saving a few keystrokes and a pair of brackets.<br>
<div>Tiny problem that I have yet to solve: you now have to explicitly give the name of all the aesthetics; aes() is sufficiently clever to guess them if they're in the right order, but the logic does not seem to carry over straightforwardly to aesDT().</div>
<div><br></div><div>I know I'll be using these, so I thought maybe other people here might be interested.</div><div><br></div></div><div>Timothee</div>