【问题标题】:Looping through elements of a list using a purrr-like function使用类似 purrr 的函数循环遍历列表的元素
【发布时间】:2021-05-10 03:36:27
【问题描述】:

我正在尝试使用类似 purrr 的函数遍历包含 NULL 对象的列表的元素。任何帮助将不胜感激。 如果可能的话,我想使用map 家族来实现这一目标

library(reprex)
library(purrr)
library(glue)
# hi, I am trying to find a way to replace the element of a list
#Data set-up

#my list
mylist=list(
  a=1,
  b=NULL,
  c=NULL,
  d=0,
  e=NULL)

# the data to repalce
ax = c(1,2,3)
bx = c(1,4,5)
cx = c(1,6,7)
dx = c(1,8,9)
ex = c(10,2,9)

#the long way
if(is.null(mylist$a)){
  mylist$a = ax
}

if(is.null(mylist$b)){
  mylist$b = bx
}

if(is.null(mylist$c)){
  mylist$c = cx
}

if(is.null(mylist$d)){
  mylist$d = dx
}

if(is.null(mylist$e)){
  mylist$e = ex
}

mylist #this what I want
#> $a
#> [1] 1
#> 
#> $b
#> [1] 1 4 5
#> 
#> $c
#> [1] 1 6 7
#> 
#> $d
#> [1] 0
#> 
#> $e
#> [1] 10  2  9

#want to create a function to change the element of a list
#and loop through all of the elements using a purrr-like function

null_funct <- function(mylist_var=mylist, var){
  if(is.null(mylist_var[[var]])){
    mylist_var[var]= glue("{var}x")
  }
  
}
list_to_loop <- c("a","b", "c", "d","e")
map(list_to_loop, null_funct, mylist_var=mylist)
#> [[1]]
#> NULL
#> 
#> [[2]]
#> NULL
#> 
#> [[3]]
#> NULL
#> 
#> [[4]]
#> NULL
#> 
#> [[5]]
#> NULL
#It does not give me the expected results

reprex package (v0.3.0) 于 2021-02-05 创建

【问题讨论】:

    标签: r list tidyverse purrr


    【解决方案1】:

    我认为这可以满足您的需求。更容易做的是将替换数据放入与 mylist 使用相同名称的命名列表中。您可以映射名称,然后在需要时从替换列表中获取替换,而不是映射列表元素。在最后展平和设置名称可以清理它。

    library(purrr)
    
    #my list
    mylist=list(
      a=1,
      b=NULL,
      c=NULL,
      d=0,
      e=NULL)
    
    # the data to repalce
    ax = c(1,2,3)
    bx = c(1,4,5)
    cx = c(1,6,7)
    dx = c(1,8,9)
    ex = c(10,2,9)
    
    #Here's my solution:
    list_names <- names(mylist)
    replace_list = list(ax, bx, cx, dx, ed) %>% set_names(list_names)
    map(list_names, ~ ifelse(is.null(mylist[[.x]]), replace_list[.x], mylist[[.x]])) %>% 
      flatten %>% 
      set_names(list_names)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-14
      • 2018-07-11
      • 1970-01-01
      • 2018-09-05
      • 2017-11-06
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      相关资源
      最近更新 更多