Reputation: 333
I am learning how to accessing list elements using lapply
and others to in complex lists. I need to set object names on certain levels but I am stuck at very beginning. So lets create list:
my_list=vector("list",3)#create empty list of 3 elements
names(my_list)=c("1st.element","2nd.eleent","3rd.element")#set names(this is easy)
my_list=lapply(my_list, function(x) x=vector("list",5))#each element is list consisting 5 elements
So now I want to set name each element. I know how to do this using for
:
for(i in 1:length(my_list)){names(my_list[[i]])=paste(names(my_list[i]),1:length(my_list[[i]]),sep=".")}
Output of this loop is my desired output. How to achieve it? I tried different approaches with lapply
the closest to code above is:
lapply(my_list[[i]],function(i)names(i)=paste(names(my_list[i]),1:length(my_list[[i]]),sep="."))
Please keep in mind I am still learning apply
functions.
Upvotes: 4
Views: 1017
Reputation: 886938
We can use Map
to loop through the names
of 'my_list' and the list
itself, then use setNames
to name the individual nested list
elements
Map(function(x, y) setNames(x, paste0(y, seq_along(x)))
, my_list, names(my_list))
A similar option using tidyverse
would be
library(purrr)
map2(my_list, names(my_list), ~ set_names(.x, paste0(.y, seq_along(.x))))
Or instead of map2
, imap
get the names of the list
as .y
(as @Moody_Mudskipper commented)
imap(my_list, ~ set_names(.x, paste0(.y, seq_along(.x))))
Upvotes: 3