我使用data.table融合函数和patterns参数编写了一个R脚本。为了获得模式,我使用了一个变量。如果我在函数之外的脚本中使用它,一切都按预期工作。如果我在函数内的脚本中使用它,则会出现错误,表示找不到函数中调用的对象。但是,如果我在全局环境中定义它,该函数可以工作!
我想知道是否有人知道为什么需要在全局env中定义变量而不是函数env?
require(data.table)
DT <- structure(list(family_id = 1:5, age_mother = c(30L, 27L, 26L, 32L, 29L),
dob_child1 = c("26/11/1998", "22/06/1996", "11/07/2002", "10/10/2004", "05/12/2000"),
dob_child2 = c("29/01/2000", NA, "05/04/2004", "27/08/2009", "28/02/2005"),
dob_child3 = c(NA, NA, "02/09/2007", "21/07/2012", NA),
gender_child1 = c(1L, 2L, 2L, 1L, 2L),
gender_child2 = c(2L, NA, 2L, 1L, 1L),
gender_child3 = c(NA, NA, 1L, 1L, NA)),
.Names = c("family_id", "age_mother", "dob_child1", "dob_child2", "dob_child3", "gender_child1", "gender_child2", "gender_child3"),
row.names = c(NA, -5L),
class = c("data.table", "data.frame"))
transpose_col <- "(^dob)|(^gender)"
# Works without problem.
melt(DT,
measure = patterns(unlist(strsplit(gsub("\\(|\\)", "", transpose_col), "\\|"))),
value.name = unlist(strsplit(gsub("\\(|\\)|\\^", "", transpose_col), "\\|")))
# Bug:
in_local_env <- function(DT) {
transpose_col2 <- transpose_col
melt(DT,
measure = patterns(unlist(strsplit(gsub("\\(|\\)", "", transpose_col2), "\\|"))),
value.name = unlist(strsplit(gsub("\\(|\\)|\\^", "", transpose_col2), "\\|")))
}
in_local_env(DT) # generate an error.
in_global_env <- function(DT) {
transpose_col3 <<- transpose_col
transpost_col4 <- transpose_col
melt(DT,
measure = patterns(unlist(strsplit(gsub("\\(|\\)", "", transpose_col3), "\\|"))),
value.name = unlist(strsplit(gsub("\\(|\\)|\\^", "", transpost_col4), "\\|")))
}
in_global_env(DT) # Works as expected.
如果我在in_local_env中调试函数并逐行执行,那么在unlist(strsplit(gsub("\\(|\\)", "", transpose_col), "\\|"))
执行问题时,熔化将无法正常工作。
我使用data.table 1.9.6