Unexpected error message while joining data.table with rbindlist() using mget()

非 Y 不嫁゛ 提交于 2021-02-09 15:22:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!