<div dir="ltr">Let's say I merge together several data.tables such that I wind up<br>with lots of NAs:<br><br>require(data.table)<br>foo <- data.table(k=1:4, foo=TRUE, key="k")<br>bar <- data.table(k=3:6, bar=TRUE, key="k")<br>
qux <- data.table(k=5:8, qux=TRUE, key="k")<br>fbq <- merge(merge(foo, bar, all=TRUE), qux, all=TRUE)<br>print(fbq)<br># k foo bar qux<br># 1: 1 TRUE NA NA<br># 2: 2 TRUE NA NA<br># 3: 3 TRUE TRUE NA<br>
# 4: 4 TRUE TRUE NA<br># 5: 5 NA TRUE TRUE<br># 6: 6 NA TRUE TRUE<br># 7: 7 NA NA TRUE<br># 8: 8 NA NA TRUE<br><br>I want to go through those columns and turn each NA into FALSE. I can<br>do this by writing code for each column:<br>
<br>fbq.cp <- copy(fbq)<br>fbq.cp[<a href="http://is.na">is.na</a>(foo), foo:=FALSE]<br>fbq.cp[<a href="http://is.na">is.na</a>(bar), bar:=FALSE]<br>fbq.cp[<a href="http://is.na">is.na</a>(qux), qux:=FALSE]<br>print(fbq.cp)<br>
# k foo bar qux<br># 1: 1 TRUE FALSE FALSE<br># 2: 2 TRUE FALSE FALSE<br># 3: 3 TRUE TRUE FALSE<br># 4: 4 TRUE TRUE FALSE<br># 5: 5 FALSE TRUE TRUE<br># 6: 6 FALSE TRUE TRUE<br># 7: 7 FALSE FALSE TRUE<br>
# 8: 8 FALSE FALSE TRUE<br><br>But I can't figure out how to do it in a loop. More precisely, I can't<br>figure out how to make the [ operator evaluate its first argument in<br>the context of the data.table. All of these have no effect:<br>
for (x in c("foo", "bar", "qux")) fbq[<a href="http://is.na">is.na</a>(x), eval(x):=FALSE]<br>for (x in c("foo", "bar", "qux")) fbq[<a href="http://is.na">is.na</a>(eval(x)), eval(x):=FALSE]<br>
for (x in c("foo", "bar", "qux")) fbq[eval(<a href="http://is.na">is.na</a>(x)), eval(x):=FALSE]<br><br>I'm running R 3.0.2 on Linux, data.table 1.8.10.<br><br>Thanks in advance,<br>John</div>