简体   繁体   English

如何使用 purrr::map 到 base::assign?

[英]How to use purrr::map to base::assign?

How to get from meow to purr?如何从喵喵叫到咕噜咕噜?

Let's say I have a list with 2 elements "a" and "b".假设我有一个包含 2 个元素“a”和“b”的列表。 I want to copy these elements into my Global environment.我想将这些元素复制到我的全局环境中。 If I wanted to just add these elements to the search path, I'd use assign.如果我只想将这些元素添加到搜索路径中,我会使用assign。 However, I want to create a copy.但是,我想创建一个副本。 And I'd like to use purrr::map to do this.我想使用 purrr::map 来做到这一点。 How does it work?它是如何工作的?

mylist <- list(a=1:2, b=3:4)

#nope
map(mylist, assign, x=names(.), value=.)

#no
map(mylist, assign(x=names(.), value=.))

#no
map2(mylist, names(mylist), assign(x=.y, value=.x) )

#no
map2(mylist, names(mylist), assign, x=.y, value=.x )

Several responses to this :-)对此的几个回应:-)

  1. Don't.别。 My first visceral and emphatic response: don't do that.我的第一个发自内心和强调的回应:不要那样做。 Very rarely do I find the use of get / assign justified, most commonly they are indications of inefficient (if not poor) data management.我很少发现使用get / assign是合理的,最常见的是它们表明数据管理效率低下(如果不是差的话)。 Having similar-structured things in a list means that you can efficiently operate on them (using map or lapply or similar).list具有相似结构的事物意味着您可以有效地对它们进行操作(使用maplapply或类似方法)。

  2. Base R does this very efficiently with list2env . Base R 使用list2env非常有效地做到了这list2env

     ls() # character(0) list2env(list(a=1:2, b=3:4), envir = .GlobalEnv) # <environment: R_GlobalEnv> ls() # [1] "a" "b"
  3. If you must use purrr , then what you need is both the name and the value, so use purrr::imap :如果您必须使用purrr ,那么您需要的是名称和值,因此请使用purrr::imap

     ls() # character(0) imap(list(a=1:2, b=3:4), ~ assign(..2, ..1, envir = .GlobalEnv)) # $a # [1] 1 2 # $b # [1] 3 4 ls() # [1] "a" "b"

    The reason your assign calls failed was that it was assigning it to the then-current environment, which is neither global nor something you get to use after your call to map / map2 .您的assign调用失败的原因是它将它分配给当时的环境,这既不是全局的,也不是您在调用map / map2后可以使用的。

Easier is list2env from base R applied directly on the named list to create the objects from the names in the global environment更容易的是来自base R list2env直接应用于命名list以从全局环境中的names创建对象

list2env(mylist, .GlobalEnv)

Regarding the use of map , it returns only the value and not the names关于map的使用,它只返回值而不返回names


A slightly related to this topic would be destructuring assignment.与此主题稍微相关的是解构赋值。 In R , this can be done with %<-% operator from zeallotR ,这可以通过zeallot %<-%操作符来zeallot

library(zeallot)
c(a, b) %<-% mylist

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM