Is there a way to get the list index name in my lapply() function?
n = names(mylist)
lapply(mylist, function(list.elem) { cat(\"What is the name of this list
Let's say we want to calculate length of each element.
mylist <- list(a=1:4,b=2:9,c=10:20)
mylist
$a
[1] 1 2 3 4
$b
[1] 2 3 4 5 6 7 8 9
$c
[1] 10 11 12 13 14 15 16 17 18 19 20
If the aim is to just label the resulting elements, then lapply(mylist,length) or below works.
sapply(mylist,length,USE.NAMES=T)
a b c
4 8 11
If the aim is to use the label inside the function, then mapply() is useful by looping over two objects; the list elements and list names.
fun <- function(x,y) paste0(length(x),"_",y)
mapply(fun,mylist,names(mylist))
a b c
"4_a" "8_b" "11_c"