1

This is my second question here. This is related to my first question here: Should I use for loop? OR apply?

I'm analyzing NHL draft data. Looking at answers to the first question, I learned to use split:

canucks_year <- split(canucks, canucks$Year)

BUT I want to make new objects, such as canucks_2000, canucks_2001 that only contain data frame of the respective years. So, I coded:

canucks_2000 <- canucks_year[["2000"]]
canucks_2001 <- canucks_year[["2001"]]
canucks_2002 <- canucks_year[["2002"]]
canucks_2003 <- canucks_year[["2003"]]

Is there any magic way to use some function in R to automate this process?

Community
  • 1
  • 1

1 Answers1

1

You can use a function called list2env, this allows you to put all elements of your list into a specified environment.

names(canucks_year) = paste0('canucks_', names(canucks_year))
list2env(canucks_year, envir = .GlobalEnv)

I first renamed the elements of your list from 2000, 2001, 2002,... to canucks_2000, canucks_2001, canucks_2002,... then used list2env to put all elements into the global environment.

acylam
  • 18,231
  • 5
  • 36
  • 45
  • Ok I get the first line. I don't understand the second line. Specifically, what is a global environment and why did you move the elements there? Thanks! –  Apr 26 '17 at 20:14
  • @JasonJoonWooBaik The global environment is the main environment where all your variables, functions and datasets are sitting in R. Basically, whenever you create a new variable like `variable = something` (not inside a function), you are placing it in your global environment. `list2env` is basically just taking all elements of your list and doing `canucks_2000 = canucks_year[["2000"]]` _for each element_. – acylam Apr 26 '17 at 20:24