Я пытаюсь понять purrr , и сейчас я работаю с pmap . pmap
может использоваться для вызова предопределенной функции и использует значения в dataframe в качестве аргументов для вызова функции. Я хотел бы знать, каково текущее состояние, так как мои data.frames могут иметь несколько тысяч строк.
Как мне распечатать текущую строку, на которой работает pmap
, возможно вместе с итогом длина data.frame?
Я попытался включить счетчик как в для l oop, а также попытался захватить текущую строку, используя
current <- data.frame(...)
а затем row.names(current)
(идея отсюда: https://blog.az.sg/posts/map-and-walk/)
, но в обоих случаях всегда печатается 1
.
Спасибо за помощь.
Для воспроизводимости давайте используем код из вопроса, который привел меня к purrr:::pmap
( Как использовать значения expand.grid для запуска различных комбинаций гиперпараметров модели для рейнджер в R ):
library(ranger)
data(iris)
Input_list <- list(iris1 = iris, iris2 = iris) # let's assume these are different input tables
# the data.frame with the values for the function
hyper_grid <- expand.grid(
Input_table = names(Input_list),
Trees = c(10, 20),
Importance = c("none", "impurity"),
Classification = TRUE,
Repeats = 1:5,
Target = "Species")
# the function to be called for each row of the `hyper_grid`df
fit_and_extract_metrics <- function(Target, Input_table, Trees, Importance, Classification, ...) {
RF_train <- ranger(
dependent.variable.name = Target,
data = Input_list[[Input_table]], # referring to the named object in the list
num.trees = Trees,
importance = Importance,
classification = Classification) # otherwise regression is performed
data.frame(Prediction_error = RF_train$prediction.error,
True_positive = RF_train$confusion.matrix[1])
}
# the pmap call using a row of hyper_grid and the function in parallel
hyper_grid$res <- purrr::pmap(hyper_grid, fit_and_extract_metrics)
Я попробовал две вещи:
counter <- 0
fit_and_extract_metrics <- function(Target, Input_table, Trees, Importance, Classification, ...) {
counter <- counter + 1
print(paste(counter, "of", nrow(hyper_grid)))
# rest of the function
}
# and also
fit_and_extract_metrics <- function(Target, Input_table, Trees, Importance, Classification, ...) {
current <- data.frame(...)
print(paste(row.names(current), "of", nrow(hyper_grid)))
# rest of the function
}
# both return
> hyper_grid$res <- purrr::pmap(hyper_grid, fit_and_extract_metrics)
[1] "1 of 40"
[1] "1 of 40"
[1] "1 of 40"
...