1

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...?

Denver Dang
  • 2,433
  • 3
  • 38
  • 68
  • Possible duplicate of [Access lapply index names inside FUN](https://stackoverflow.com/questions/9950144/access-lapply-index-names-inside-fun) – GoGonzo Sep 26 '17 at 14:04

3 Answers3

1

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]]))
})
Andre Elrico
  • 10,956
  • 6
  • 50
  • 69
0

This can be done, all you have to do is name the list:

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("one" = list1, "two" = list2, "three" = list3)

names(dataset)

My suggestion would be to use purrr code for your problem:

library(purrr)
dataset %>% map(mean)
Hanjo Odendaal
  • 1,395
  • 2
  • 13
  • 32
0

This looks like a good use for the lapply and names functions. lapply conveniently applies the same function to each element of a list, thus bypassing a for loop.

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)
names(dataset) <- c("list1", "list2", "list3")

lapply(dataset, mean)
$list1
[1] 5.5

$list2
[1] 6.5

$list3
[1] 7.5
rfraser
  • 11
  • 2