Denver Dang Denver Dang - 5 months ago 46
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) {

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) {

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)

    paste("Name:", names(dataset[x]),"Mean:", mean(dataset[[x]]))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download