问题
I'm trying to conduct a certain a calculation using purrr::map2() taking two different arguments.
purrr::map2(
.x = c(1, 3),
.y = c(10, 20),
function(.x, .y)rnorm(1, .x, .y)
)
purrr::map2() returns a list, but I want to assign a distinct object name to each content within the list. For example, I want to name the first list [[1]] [1] -5.962716 as model1 and [[2]] [1] -29.58825 as model2. In other words, I'd like to automate the object naming like model* <- purrr::map2[[*]]. Would anybody tell me a better way?
> purrr::map2(
+ .x = c(1, 3),
+ .y = c(10, 20),
+ function(.x, .y)rnorm(1, .x, .y)
+ )
[[1]]
[1] -5.962716
[[2]]
[1] -29.58825
This question is similar to this, though note that I need the results of the calculation in separate objects for my purpose.
回答1:
You could assign the name to the result using setNames :
result <- purrr::map2(
.x = c(1, 3),
.y = c(10, 20),
function(.x, .y)rnorm(1, .x, .y)
) %>%
setNames(paste0('model', seq_along(.)))
Now you can access each individual objects like :
result$model1
#[1] 6.032297
If you want them as separate objects and not a part of a list you can use list2env.
list2env(result, .GlobalEnv)
来源:https://stackoverflow.com/questions/64572192/giving-a-different-object-name-for-the-content-of-the-returned-list-of-purrrma