[英]Map a list of params to a function using purrr and save the output back to the list
我在嘗試將嵌套列表中的 map 參數用於 function 時遇到問題。使用purrr::map
時,我無法將值分隔為 arguments 而是將子列表傳遞給.x
。 我可以用lapply
做到這一點,但想知道一個purrr
解決方案。
最終,我想將每個子列表的參數傳遞到一個 function 中,然后將 function 的 output 保存為每個子列表中的新項目。
library(data.table)
library(highcharter)
library(lubridate)
library(purrr)
library(tidyr)
plot_map = list(
apples = list(
y_val = "apples",
name = "Apples",
title = "Daily Apples"
),
oranges = list(
y_val = "oranges",
name = "Oranges",
title = "Daily Oranges"
),
pears = list(
y_val = "pears",
name = "Pears",
title = "Daily Pears"
),
bananas = list(
y_val = "bananas",
name = "Bananas",
title = "Daily Bananas",
y_title = "Not Count"
)
)
d = as_date("2022-11-29")
set.seed(10)
# dummy data
d_t = data.table(
date = seq(floor_date(d, "month"), rollforward(d), by = "day"),
apples = round(abs(rnorm(1:30) * 10),0),
oranges = round(abs(rnorm(1:30) * 15),0),
pears = round(abs(rnorm(1:30) * 20),0),
bananas = round(abs(rnorm(1:30) * 5),0)
)
create_hc_plot = function(y_val, name, title, y_title = "Count") {
highchart(type = "chart") %>%
hc_title(text = title) %>%
hc_add_series(d_t, hcaes(x = date, y = !!y_val), type = "line", name = name) %>%
hc_xAxis(type = "datetime") %>%
hc_yAxis(title = list(text = y_title))
}
現在整個子列表被傳遞到.x
而不是將每個命名參數和參數映射到create_hc_plot
。
plot_map %>%
map(., ~ create_hc_plot(unlist(.x)))
# or
plot_map %>%
map(., create_hc_plot, unlist(.x))
# Error in `dplyr::mutate()`:
# ! Problem while computing `y = c(y_val = "apples", name = "Apples", title = "Daily Apples")`.
# ✖ `y` must be size 30 or 1, not 3.
如上所述,所需的 output 會將 plot 的結果保存到調用它的同一子列表中。
plot_map[['apples']]
# $y_val
# [1] "apples"
#
# $name
# [1] "Apples"
#
# $title
# [1] "Daily Apples"
#
# $plot
# HC PLOT here
create_hc_plot create_hc_plot()
) 中的unlist(.x)
不是三個 arguments,而是創建一個參數,一個向量c(y_val = "apples", name = "Apples", title = "Daily Apples")
。 你想使用類似do.call
的東西:
map(plot_map, ~ do.call(create_hc_plot, .x))
哪個正確地繪制了每張圖。
快速搜索了一下,我找不到如何將 highcharts 保存到對象/列表元素中,所以我不知道這是否可行。 如果是這樣,您也許可以執行以下操作:
plot_map = map(plot_map, ~ c(., plot = list(do.call(create_hc_plot, .x))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.