Creating Multiple Data Frames with map_dfr

I am taking a data frame containing data from federal elections. One of the variables is state. I want to create a data frame for every state separately. This is my code that I have so far, but it makes one data frame with each state's data stacked on top of each other. Any help is appreciated! Thank you!

``` r
separate_by_state <- function(n){
  "n" <- elections %>%
    filter(state == "n")

states <- c("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Dist. of Col.", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming")

state_df <- map_df(states, separate_by_state)
#> Error in map_df(states, separate_by_state): could not find function "map_df"

Created on 2019-10-11 by the reprex package (v0.3.0)

I might suggest the following code to put the data for each state into a separate tibble and form a list-column of these tibbles.

elections %>%

This assumes you have a column in your data set indicating state membership. We don't know what your data looks like though, so your reprex might be incomplete.

Thank you! With this, I was able to successfully create a list-column of the tibbles.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.