Javier Lopez Tomas
Javier Lopez Tomas

Reputation: 2342

How to create dataframes iterating over a list of names?

I have this dataframe:

x = data.frame("city" = c("Madrid","Berlin","Florence","Madrid"), 
"Visits" = c(100,200,80,38), "Date" = c(1,2,3,4))

From that sample, I would like to obtain 3 dataframe (one for each city) with all the values containing that city and named as that city without the column city, so it would result in the following:

Madrid = data.frame("Visits" = c(100,38), "Date" = c(1,4))
Berlin = data.frame("Visits" = c(200), "Date" = c(2)
Florence = data.frame("Visits" = c(80), "Date" = c(3))

I asked the same question in pandas: How to create dataframes iterating over a set? but I cannot find something similar to dictionary comprehension.

I have managed to get the unique list and to get the values of a city:

cities = unique(select(x,city))
for (i in cities){
  dplyr::filter(x,city == i)}

I know that loops should not be used in R and apply is more efficient, but I dont know how could I do that using apply. I am open to other data structures (and not dataframes for each city) as long as I am able to access them easily to pass other functions (auto.arima for instance). Thank you very much

Upvotes: 0

Views: 62

Answers (1)

Aurèle
Aurèle

Reputation: 12819

You could do

list_dfs <- split(x, x$city)

to assign the result of split to a variable, and then access an individual data frame with e.g. list_dfs$Madrid.


If you're more comfortable having the data frames as individual variables in your Global environment (see https://stackoverflow.com/a/9726880/6197649), you could do

list2env(split(x, x$city), envir = .GlobalEnv)

but that is not the recommended "R way of doing things". It's usually better to have similarly structured objects in a single list.

Upvotes: 1

Related Questions