I am creating a series of data.tables via a loop where each tables name and columns are dependent on the loop.
I found I can use assign
to create the table and then use eval(as.name(tbl))
to then call it which seems to work ok. The column name doesn't seem to be behaving quite like I want though?
To generate the column name I use capture.output(str(tbl, give.head = F))
which works but then when I want to reference the column it is surrounded by double quotes e.g. "name_win_pcnt"
I can't seem to reference the column either so if I use name_win_pcnt$"name_win_pcnt" I get a NULL in the console.
Here is an example.
require(data.table)
# initial data table
dt <- data.table(x = rnorm(10),
y = rnorm(10),
grp = c(rep("a",3), rep("b",7))))
#variables
metric <- c("win", "place")
cols <- "name"
tbl <- paste0(cols, "_", metric[1],"_pcnt")
# create new table and create new column
assign(tbl, dt, envir = .GlobalEnv)
eval(as.name(tbl))[, capture.output(str(tbl, give.head = F)) := 0L, by = .(grp)]
If I now try and update the new column using
eval(as.name(tbl))[, eval(tbl) := 1L, by = .(grp)]
this creates me a new column but leaves the old one?
I tried adding the column using eval(as.name(tbl))[, eval(tbl) := 0L]
but then when I try and update it I get an error:
Error in is.nan(name_win_pcnt) :
default method not implemented for type 'list'
assign
. Put all these data.tables in a list.assign
is for experts who know when it is needed (almost never). Using a list (or environment) is the "R way".