0

I would like to have a list where each item is "Born in " each of the cities of the cities vector.

cities <- c("Lausanne", "Zurich", "Geneva")

mylist <- list()

for (i in 1:length(cities)){
  for (city in cities){
    born <- paste0("Born in ", city)
    mylist[[i]] <- born
  }
}

I need it in the list format because I have much more complex data and would actually be adding dataframes into the list. I would like to understand how the double loop would work (one for items and one for length).

Thank you!

InesGuardans
  • 129
  • 10

1 Answers1

2

If you want to put the data in list you can use as.list

as.list(paste0("Born in ", cities))

#[[1]]
#[1] "Born in Lausanne"

#[[2]]
#[1] "Born in Zurich"

#[[3]]
#[1] "Born in Geneva"

If you really want to use for loop, you'll need only one loop

mylist <- vector("list", length(cities))
for (i in seq_along(cities)) {
    mylist[[i]] <- paste0("Born in ", cities[i])
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213