[Edit] Working with the idea of using get
to pull in values referenced by column names that I saw in an answer from Matthew Dowle this seems to be effective:
setkey(DT, currency)
DT[ , cvt := .SD[, get(currency)]*price, by=currency]
DT
day price currency aud eur cvt
1: 1 0.30776611 aud 1.624996 2.035811 0.5001188
2: 3 0.55232243 aud 1.280354 2.038349 0.7071681
3: 5 0.46854928 aud 1.762551 1.920101 0.8258420
4: 7 0.81240262 aud 1.204612 2.270302 0.9786301
5: 9 0.54655860 aud 1.359475 2.049097 0.7430328
6: 2 0.25767250 eur 1.882166 2.210804 0.5696634
7: 4 0.05638315 eur 1.398488 2.248972 0.1268041
8: 6 0.48377074 eur 1.669022 1.671420 0.8085842
9: 8 0.37032054 eur 1.357525 2.381954 0.8820863
10: 10 0.17026205 eur 1.690291 1.777724 0.3026789
Here's one method although it doesn't generalize well to larger number of currencies:
DT[ , cvt := ifelse (currency == 'aud', price*aud, price*eur) ]
> DT
day price currency aud eur cvt
1: 1 0.30776611 aud 1.624996 2.035811 0.5001188
2: 2 0.25767250 eur 1.882166 2.210804 0.5696634
3: 3 0.55232243 aud 1.280354 2.038349 0.7071681
4: 4 0.05638315 eur 1.398488 2.248972 0.1268041
5: 5 0.46854928 aud 1.762551 1.920101 0.8258420
6: 6 0.48377074 eur 1.669022 1.671420 0.8085842
7: 7 0.81240262 aud 1.204612 2.270302 0.9786301
8: 8 0.37032054 eur 1.357525 2.381954 0.8820863
9: 9 0.54655860 aud 1.359475 2.049097 0.7430328
10: 10 0.17026205 eur 1.690291 1.777724 0.3026789
You get a warning (and different results if you try wit if(.){.}else{.}
with:
DT[ , cvt := if (currency == 'aud'){price*aud}else{price*eur}]
This is completely analogous to what happens with data.frames. But ... using ifelse
in data.table is known to be slow.