为 purrr::map2() 的返回列表的内容提供不同的对象名称 [英] Giving a different object name for the content of the returned list of purrr::map2()

查看:44
本文介绍了为 purrr::map2() 的返回列表的内容提供不同的对象名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 purrr::map2() 采用两个不同的参数进行某种计算.

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() 返回一个列表,但我想为列表中的每个内容分配一个不同的对象名称.例如,我想将第一个列表 [[1]] [1] -5.962716 命名为 model1[[2]] [1] -29.58825 作为 model2.换句话说,我想像 model* <- purrr::map2[[*]] 一样自动化对象命名.有人能告诉我更好的方法吗?

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.

推荐答案

您可以使用 setNames 为结果指定名称:

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


如果您希望它们作为单独的对象而不是列表的一部分,您可以使用 list2env.

list2env(result, .GlobalEnv)

这篇关于为 purrr::map2() 的返回列表的内容提供不同的对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆