I create a list called list_ok:
list_ok <- list()
a=c(1,2,3,4,5)
b=c(6,7,8,9,10)
c=c(11,12,13,14,15)
d=c(16, 17, 18, 19, 20)
e=c(21,22,23,24,25)
list_ok[[1]]=a
list_ok[[2]]=b
list_ok[[3]]=c
list_ok[[4]]=d
list_ok[[5]]=e
This code below, creates the same list_ok by using a for loop:
new_list <- vector(mode = "list", length=5)
for (i in 1:5) {
for(k in 1:5) {
new_list[[i]][k] <- list_ok[[i]][k]
}
}
> new_list
How can I do the same exercise using the map function? My problem is to know how to deal with the two different indexes (i and k) in map function.
I will use the same idea in another exercise wich is more complex.
Any help?
new_listandlist_okare identical. Why do you want to create an identical copy of alistwith aforloop (or withpurrr::map)? This sounds like an XY problem to me. Can you provide a few more details?new_list <- map(list_ok, I)would create an identical copy ofok_list. But in that case why not justnew_list <- list_ok?mapis that it allows for vectorised functions, i.e. loop throw the elements of alistand then apply a vectorised function on its elements. Thinking about this in terms of 2 "array" indices is the wrong way to think aboutmap(or*applyfor that matter), and you end up with convoluted solutions like the ones presented below. If you must use array indices, use aforloop; there is nothing wrong withforloops in R, provided you use them correctly!