broccoli
broccoli

Reputation: 4846

Creating new data.table columns within a for-loop not showing up

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.

Upvotes: 2

Views: 111

Answers (1)

Esther
Esther

Reputation: 1115

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
}

Upvotes: 2

Related Questions