You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言purrr::map系列如何仅迭代一个输入、传入固定参数

解决方案

该需求完全可以实现。你之前使用map2()报错的原因是map2()的设计逻辑是并行遍历两个长度相同的输入序列,每次调用分别取两个序列的第i个元素传入自定义函数,你传入的数据集长度和待遍历变量向量长度不一致,因此触发维度报错。

这个场景不需要使用map2(),直接使用purrr::map原生支持的固定参数传递特性即可:map系列函数中,.f参数之后传入的所有参数都会原样传递给每次调用的目标函数,不会参与遍历。

第一步:改写自定义函数

新增数据集作为第二个入参即可:

matching_fcn <- function(.x, df){
  
  matching_df <- df %>% 
  mutate(wc = case_when(wc == "yes" ~ "TRUE", 
                        wc == "no" ~ "FALSE")) %>% 
  drop_na(k5, k618, age, wc, hc, .x)

  matching_df$wc <- as.logical(matching_df$wc)
  ps1 <- glm(wc ~ k5 + k618 + age + hc, 
             family = binomial, data = matching_df)
  
  pscore <- ps1$fitted.values
  matching_df <- cbind(matching_df, pscore)
  
  Y <- matching_df[[.x]]
  Tr <- as.logical(matching_df$wc)
  
  psm1 <- Matching::Match(
    Y = Y, 
    Tr = Tr, 
    X = pscore, 
    estimand = "ATT", 
    M = 1, 
    replace = TRUE, 
    caliper = 0.05, 
    version = "fast")
  p <- 1 - pnorm(abs(psm1$est.noadj/psm1$se.standard))
  with(psm1, tibble(dv=.x, est=est.noadj, se=se.standard, p=p, ndrops=ndrops))
}

第二步:调用函数传入不同数据集

只需要在map_df的.f参数之后指定传入的数据集即可:

  • 适配原Mroz数据集调用:
purrr::map_df(
  .x = tidyselect::all_of(vars),
  .f = matching_fcn,
  df = Mroz
)
  • 适配其他数据集调用:
# 传入df1
purrr::map_df(
  .x = tidyselect::all_of(vars),
  .f = matching_fcn,
  df = df1
)

# 传入df2
purrr::map_df(
  .x = tidyselect::all_of(vars),
  .f = matching_fcn,
  df = df2
)

特殊场景:如果确实需要用map2实现

如果你有特殊逻辑必须用map2,可以将数据集包装为和变量向量长度一致的重复列表即可,不过该写法没有必要,仅作参考:

purrr::map2_df(
  .x = tidyselect::all_of(vars),
  .y = rep(list(df1), length(vars)),
  .f = matching_fcn
)

内容的提问来源于stack exchange,提问作者C.Robin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:54:03