尝试访问多个列时出现异常行为

时间:2019-04-10 09:54:03

标签: r data.table

在非等式合并中访问j中的变量时遇到一些麻烦。

library(data.table)

DT = data.table(x=rep(c("b","a","c"),each=3), y=c(1,3,6), v=1:9, date = seq(as.Date("2019-03-15"), by ="days", length.out = 9))
DTI <- data.table(date = as.Date(c("2019-03-16", "2019-03-21")), size = 55, len = c(3, 4), len2 = c(5, 5))


len_var <- "i.len"


DT[DTI, {
  ct <- len;
  mm <- len2
  print(paste0("ct :", ct))
  print(paste0 ("mm: ", mm))
  i_min <- min(which(y > ct));
  i_min
},
on = .(date > date),
by = .EACHI, allow.cartesian = TRUE, verbose = FALSE]

# [1] "ct :3"
# [1] "mm: 5"
# [1] "ct :4"
# [1] "mm: 5"
# date V1
# 1: 2019-03-16  1
# 2: 2019-03-21  2


# works
DT[DTI, {
  ct <- get(len_var);
  mm <- get("len2") # this variable causes issue in the following examples
  print(paste0("ct :", ct))
  print(paste0 ("mm: ", mm))
  i_min <- min(which(y > ct));
  i_min
},
on = .(date > date),
by = .EACHI, allow.cartesian = TRUE, verbose = FALSE]

# [1] "ct :3"
# [1] "mm: 5"
# [1] "ct :4"
# [1] "mm: 5"
# date V1
# 1: 2019-03-16  1
# 2: 2019-03-21  2

#error ???
DT[DTI, {
  ct <- len;
  mm <- get("len2")
  print(paste0("ct :", ct))
  print(paste0 ("mm: ", mm))
  i_min <- min(which(y > ct));
  i_min
},
on = .(date > date),
by = .EACHI, allow.cartesian = TRUE, verbose = FALSE]

# Error in validate(cols, x) : 
#   cols value [len] not present (or out of range) in x

最后一个表达式不起作用。为什么?如果我将mm <- get("len2")更改为mm <- len2,它将起作用,但是我想动态地将某些变量传递给该列。也就是说,这可行:

DT[DTI, {
  ct <- len;
  mm <- len2
  print(paste0("ct :", ct))
  print(paste0 ("mm: ", mm))
  i_min <- min(which(y > ct));
  i_min
},
on = .(date > date),
by = .EACHI, allow.cartesian = TRUE, verbose = FALSE]

1] "ct :3"
[1] "mm: 5"
[1] "ct :4"
[1] "mm: 5"
         date V1
1: 2019-03-16  1
2: 2019-03-21  2

这是怎么回事?我想念什么吗?这是data.table中的预期行为吗?也就是说,您需要以相同的方式(通过合并编码i来统一使用x[i, ]来从get()合并中的GeckoHtmlElement form = browser.Document.GetElementsByTagName("form")[0]; Listener ear = new Listener(); ear.OnSubmit += Ear_OnSubmit; form.GetEventTarget().AddEventListener("onsubmit", ear, true, false, 0); 数据表访问变量(列)的方式访问每个变量)。

1 个答案:

答案 0 :(得分:2)

我们可以将其转换为符号(as.nameas.symbol),并且应该可以使用

DT[DTI, {
    ct <- len;
     mm <- as.name("len2")
     print(paste0("ct :", ct))
     print(paste0 ("mm: ", mm))
     i_min <- min(which(y > ct));
     i_min
    },
    on = .(date > date),
      by = .EACHI, allow.cartesian = TRUE, verbose = FALSE]