问题
While preparing this answer, I've got the error message
Error: value for ‘spine_hlfs’ not found
from running
setDT(giraffe)[rbindlist(mget(df_names), idcol = "df.name"), on = "runkey", project := df.name][]
while
df_list <- mget(df_names)
setDT(giraffe)[rbindlist(df_list, idcol = "df.name"), on = "runkey", project := df.name][]
works as expected.
Before reporting an issue on github, I want to verify with the community that this indeed is a bug or if there is a simple explanation for the error message which I'm unaware of.
Reproducible example
set.seed(123L)
giraffe <- data.frame(runkey = 1:500,
X2 = sample.int(99L, 500L, TRUE),
X3 = sample.int(99L, 500L, TRUE),
X4 = sample.int(99L, 500L, TRUE),
project = "",
stringsAsFactors = FALSE)
spine_hlfs <- data.frame(runkey = c(1L, 498L, 5L))
ir_dia <- data.frame(runkey = c(3L, 499L, 47L, 327L))
df_names <- c("spine_hlfs", "ir_dia")
library(data.table)
# this creates the error message
setDT(giraffe)[rbindlist(mget(df_names), idcol = "df.name"), on = "runkey", project := df.name][]
## Error: value for ‘spine_hlfs’ not found
# this works as expected
df_list <- mget(df_names)
setDT(giraffe)[rbindlist(df_list, idcol = "df.name"), on = "runkey", project := df.name][]
回答1:
This is basically because (unlike get
) mget
has inherits = FALSE
as default. Hence it only looks in the local environment. Changing to mget(df_names, inherits = TRUE)
(or, if you want to be explicit to mget(df_names, envir = .GlobalEnv)
) should fix this.
This was independently reported by @Arun on GH a while ago and he intends to change the default behavior of mget
(while used within a data.table
) to be consistent with get
in the future, so stay tuned.
来源:https://stackoverflow.com/questions/47679905/unexpected-error-message-while-joining-data-table-with-rbindlist-using-mget