Denver Dang Denver Dang - 22 days ago 8
R Question

Print out the name of a list in list in R?

Sorry for the cryptic headline.

However, it is rather simple. I have a list that contains several lists, for example:

list1 <- c(1,2,3,4,5,6,7,8,9,10)
list2 <- c(2,3,4,5,6,7,8,9,10,11)
list3 <- c(3,4,5,6,7,8,9,10,11,12)

dataset <- list(list1, list2, list3)


So if I wanna do some looping with this It could look like:

for (data in dataset) {
mean(data)
}


However, depending on the number of lists inside the dataset list one might to know which list the calculated mean belongs to. So in principle I would like it to say:

for (data in dataset) {
print(name-of-list-inside-dataset-list)
mean(data)
}


Can this be done, or...?

Answer Source

First set the names of the list elements: Shamelessly stolen from @Hanjo Jo'burg Odendaal

dataset <- list("one" = list1, "two" = list2, "three" = list3)

Then print the name and mean: (no packages needed and lightning fast)

lapply(seq_along(dataset),function(x){
    paste("Name:", names(dataset[x]),"Mean:", mean(dataset[[x]]))
})