0

I have a that contains year, state, and organization type. The years range from 1970-2018, and there are 6 (or so) types of organizations. I want to separate this dataframe by year and organization.

An example of what I have:

Year  State  Type
   1970   AL     A
   1970   AK     B
   .....
   .....
   1975   OH     D

What I would like:

Dataframe 1

  1970  AL     A
  1970  AK     A

Dataframe 2

  1971  AL     A
  1971  AK     A

Dataframe 50

  1970 AL   G
  1970 AK   G

Dataframe 55

  2018 AL   G
  2018 AK   G

I have thought some loop/while function could work but have not figured it out. I could subset manually but that will take a lot of time. Thank you for your help.

JeffB
  • 83
  • 9
  • 3
    Try `split(df, df$Type)` – Sotos Mar 13 '20 at 15:32
  • I have tried this, but it puts everything into a list. Not sure how to get these components into individual dataframes? – JeffB Mar 13 '20 at 15:42
  • 3
    Each list element is an individual data frame. Do you mean that you want them all listed in your global environment? It's a bad practice. Preferred way is to keep them in the list and simply save the list. If you really want to put them to your global env. then follow [this link](https://stackoverflow.com/questions/13795526/return-elements-of-list-as-independent-objects-in-global-environment) has the information you need. Note you can extend `split` to include more columns if needed – Sotos Mar 13 '20 at 15:46
  • I want to add these data to a larger data set for analyses. I have tried the: do.call("cbind", Dataframe) but get this in error: In cbind(AR = c(1970, 1970, 1970, 1970, 1970, 1970, 1970, 1970, : number of rows of result is not a multiple of vector length (arg 1) The split function is actually exactly what I want. Thank you for your help, it is much appreciated. – JeffB Mar 13 '20 at 15:59
  • *"add ... to a larger data set"* suggests `do.call("rbind",...)`, not cbind. One good reference for list-of-frames: https://stackoverflow.com/a/24376207/3358272 – r2evans Mar 13 '20 at 16:49

0 Answers0