Giving a different object name for the content of the returned list of purrr::map2()

◇◆丶佛笑我妖孽 提交于 2021-01-28 07:14:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!