当我映射包含 grf::causal_forest() 的函数时,R 告诉我向量不是向量

R telling me vectors are not vectors when I map function that includes grf::causal_forest()

我想将列名向量传递给 purrr::map(),然后将它们迭代传递给 grf::causal_forest() 函数。在尝试这样做时,我得到一个错误,我传递给 causal_forest() 的值不是向量(这是必需的),即使它们肯定是。

比如我有这个df

n <- 500
p <- 5
X <- matrix(rnorm(n * p), n, p)
W <- rbinom(n, 1, 0.5)
Y1 <- pmax(X[, 1], 0) * W + X[, 2] + pmin(X[, 3], 0) + rnorm(n)
Y2 <- pmax(X[, 1], 0) * W + X[, 2] + pmin(X[, 3], 0) + rnorm(n)
Y3 <- pmax(X[, 1], 0) * W + X[, 2] + pmin(X[, 3], 0) + rnorm(n)
df <- data.frame(Y1, Y2, Y3, W, X)

head(df)

          Y1           Y2          Y3 W           X1         X2          X3          X4          X5
1  0.5457143  1.933581483  2.38474639 1 -0.788463384  0.9146194  0.73684926 -0.51268651 -0.53317046
2  0.9640213 -1.098133573  1.15639726 1  0.008873619  1.1513535 -1.09108874  0.10308198  1.46560149
3  0.8839862  0.005357524  1.26430215 1  1.588380125 -0.9261196  0.35219255  0.81017210 -1.86847771
4  0.1424579 -0.783984941 -0.01038922 0  2.391068797  0.3080699 -0.94651780  1.92707015  0.42646239
5  0.1771250  0.484711614 -1.95481918 1  0.058835623  0.2541232 -0.05696465  0.01781394 -0.07254417
6 -1.8144585 -1.972902090 -1.47101855 1 -0.518724916 -1.1474859  0.94850272  0.80635703  0.72156403

其中Y*为因变量,X*为协变量矩阵,W为二元处理指标。我可以用 Y* 的单个值来估计模型,就像这样

library(grf)

c_forest <- causal_forest(
  X = X, 
  Y = df$Y1, 
  W = df$W)

ate_c_forest <- average_treatment_effect(
  c_forest, 
  target.sample = "overlap")

ate_c_forest

  estimate    std.err 
0.12262543 0.09578717 

但我想使用 map() 遍历 Y1Y2Y3 的每个值,然后提取 estimatestd.err 用于每次调用 average_treatment_effect() 的输出,并将它们放在 tibble 中。所以我写了这个小函数

Y_n <- c("Y1", "Y2", "Y3")
names(Y_n) <- Y_n

grf_fcn <- function(.x){
  Y <- df$.x
  W <- df$W
  
  c_forest <- causal_forest(
    X = X,
    W = W,
    Y = Y)
  
  ate_c_forest <- average_treatment_effect(
    c_forest, 
    target.sample = "overlap")
}

## call function
library(purrr)

grf_results <- purrr::map(
  .x = tidyselect::all_of(Y_n),
  .f = grf_fcn)

但是,当我尝试调用该函数时 returns 错误“Error in validate_observations(Y, X) : Observations (W, Y, Z or D) must be vectors.” 我觉得这很好奇,因为 Y*W 个向量。例如

> is.vector(df$Y1)
[1] TRUE
> is.vector(df$W)
[1] TRUE

谁能看出我哪里错了?或者这是某种错误?

为了更好地了解您的函数中的问题出在哪里,请比较以下对 map.

的两次调用的输出

这个就是你用的那个,会return NULL:

purrr::map(tidyselect::all_of(Y_n), function(x) { df$x })

这个使用括号表示法,它将return预期值:

purrr::map(tidyselect::all_of(Y_n), function(x) { df[[x]] })

这是 map 的一个怪癖,老实说,我不太确定幕后发生了什么,但至少我们知道如何修改您的函数以获得您想要的结果:

grf_fcn <- function(x){
  Y <- df[[x]]
  W <- df$W
  
  c_forest <- causal_forest(
    X = X,
    W = W,
    Y = Y)
  
  ate_c_forest <- average_treatment_effect(
    c_forest, 
    target.sample = "overlap")
}