1

this is my first post.

I have this dataframe of the Nhl draft. What I would like to do is to use some sort of recursive function to create 10 objects.

So, I want to create these 10 objects by subsetting the Nhl dataframe by Year. Here are the first 6 rows of the data set (nhl_draft)

Year Overall                  Team
1 2000       1    New York Islanders
2 2000       2     Atlanta Thrashers
3 2000       3        Minnesota Wild
4 2000       4 Columbus Blue Jackets
5 2000       5    New York Islanders
6 2000       6   Nashville Predators
            Player    PS
1    Rick DiPietro  49.3
2     Dany Heatley  95.2
3   Marian Gaborik 103.6
4 Rostislav Klesla  34.5
5     Raffi Torres  28.4
6   Scott Hartnell  74.5

I want to create 10 objects by subsetting out the Years, 2000 ~ 2009. I tried,

for (i in 2000:2009) {
  nhl_draft.i <- subset(nhl_draft, Year == "i")
}

BUT this doesn't do anything. What's the problem with this for-loop? Can you suggest any other ways?

Please tell me if this is confusing after all, this is my first post......

Jaap
  • 81,064
  • 34
  • 182
  • 193
  • 2
    How about use `split` to separate all the data? `nhl_list <- split(nhl_draft, f = nhl_draft$Year)` – www Apr 24 '17 at 18:48
  • `L <- split(nhl_draft, nhl_draft$Year)` makes a list of dataframes, for each `$Year` a dataframe. (as @ycw said) – jogo Apr 24 '17 at 19:00

1 Answers1

3

The following code may fix your error.

# Create an empty list
nhl_list <- list()

for (i in 2000:2009) {
  # Subset the data frame based on Year
  nhl_draft_temp <- subset(nhl_draft, Year == i)
  # Assign the subset to the list
  nhl_list[[as.character(i)]] <- nhl_draft_temp
}

But you can consider split, which is more concise.

nhl_list <- split(nhl_draft, f = nhl_draft$Year)
www
  • 38,575
  • 12
  • 48
  • 84
  • How do i convert nhl_list into a data frame? –  Apr 24 '17 at 19:30
  • Are you talking about access one of the subset in `nhl_list`? You can access each data frame by calling the name of the data frame. In this case, the name is `Year`. For example, `nhl_list[["2000"]]` is the subset from `2000`. Please note that use double bracket and enclose the number of year in "". – www Apr 24 '17 at 19:38