使用 purrr 生成模型的强制错误

Coercion error using purrr to generate models

为了提高我对 R 库 purrr 和 dplyr 的理解,我正在研究 Hadley Wickham 描述的一个示例,使用不同的模型和数据集拆分。但是,我 运行 在使用多个参数时陷入强制错误,例如使用 map2() 和 pmap():

(list) object cannot be coerced to type 'integer'

我已经简化了我的软件,试图通过使用以下内容来确定我出错的地方:

    library(dplyr)
    library(purrr)
    library(randomForest)

    # generate a list of data frames ( using the iris data set )

    data_list <- lapply(1:10, FUN = function(x) iris)

    # generate a list of parameters:

    param_list <- as.list(seq.int(100,1000, by = 100))

    # - following works

    models <- data_list %>% map(~randomForest(Species ~., data = .))

   # - following works

    models <- seq_along(param_list) %>% 
              map(~randomForest(Species ~., data = data_list[[.]],
                                           ntree = param_list[[.]]))

    # - following has error: Error in randomForest.default(m, y, ...) : 
    #     (list) object cannot be coerced to type 'integer'

     models <- map2(data_list, param_list, 
                 ~randomForest(Species ~., data = ., ntree = .))

几天来我一直在为这个问题苦苦挣扎,因此我可能对列表、数据框等感到困惑,因此感谢您的帮助。

你应该没问题:

models <- map2(data_list, param_list, 
               ~randomForest(Species ~., data = .x, ntree = .y))

map2 中,公式 RHS 上匿名函数的隐式参数是 .x.y.