【发布时间】: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 创建
【问题讨论】: