Looping through elements of a list using a purrr-like function

I am trying to loop through elements of a list containing NULL object using a purrr-like function. Any help would be greatly appreciated. I would like to do it using the map family to achieve this if possible

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

Created on 2021-02-05 by the reprex package (v0.3.0)

I would use map2() and store the replacement data in a list. Will that work for you?

library(purrr)
mylist=list(
   a=1,
   b=NULL,
   c=NULL,
   d=0,
   e=NULL)
 
 # the data to repalce
RplcList <- list(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))
 
null_funct <- function(A, B){
   if(is.null(A)) return(B) else return(A)
 }
map2(mylist, RplcList, null_funct)
$a
[1] 1

$b
[1] 1 4 5

$c
[1] 1 6 7

$d
[1] 0

$e
[1] 10  2  9
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.