2

I'm trying to create column names within a for-loop. For instance say I have the following data.table

dt = structure(list(id = c("a", "b", "c"), val = c(1, 4, 6)), .Names = c("id", 
"val"), row.names = c(NA, -3L), class = c("data.table", "data.frame"
))

I run a for-loop as follows

for(i in seq(1:1)) { # 1:1 not a bug. 
  varname = 'flag1'
  cname = 'val'
  threshold = 4
  expr = parse(text=paste0(varname, ' := (', cname, ' > ', threshold, ')'))
  dt[, eval(expr)]
}

Somehow, when I don't use the for loop and just set i=1, this works, i.e. a new column called flag1 gets created. But if I run it with the for loop the data.table and I do print(dt) I get nothing. Could someone point out what I'm doing wrong? My real use case involves creating boolean column names within a for loop which gets applied to columns which are themselves stored as a vector of strings. Any pointers appreciated.

smci
  • 32,567
  • 20
  • 113
  • 146
broccoli
  • 4,738
  • 10
  • 42
  • 54
  • 1
    First line lacks closing parenthesis. – Hugh May 23 '18 at 23:03
  • Fyi, there's also `dt[, (varname) := get(cname) > threshold]` for that, or maybe `dt[, (varname) := get(cname) > ..threshold]` in the current version (which I can't test on at the moment). – Frank May 24 '18 at 00:04
  • Possible duplicate of [data.table objects not printed after returned from function](https://stackoverflow.com/questions/32988099/data-table-objects-not-printed-after-returned-from-function) – smci May 25 '18 at 10:09

1 Answers1

2

I think this might be a duplicate of this issue data.table objects not printed after returned from function

Try adding a second set of square brackets to the last line of the loop

for(i in seq(1:1)){ 
varname = 'flag1'
cname = 'val'
threshold = 4
expr = parse(text=paste0(varname, ' := (', cname, ' > ', threshold, ')'))
df[, eval(expr)][] #add brackets here
}
Esther
  • 1,115
  • 1
  • 10
  • 15
  • Really weird, but it fixed my issue! Thanks. I just wish this came up easier in Google searches, I searched a lot with different ways to phrase this, but none came up. – broccoli May 23 '18 at 23:38