Aaron
Aaron

Reputation: 181

For loop to create new objects in R

I'm trying to create new objects for each item in the column "category."

rs_ <- regular_season %>% filter(user_id > 0)
unique_categories <- unique(regular_season$category)

for (i in unique_categories)
  rs_[i] <- regular_season %>% filter(category %in% unique_categories)

I've tried to create a template object "rs_" that I would iteratively add to (it's essentially the dataset with a null condition on it, just so it doesn't simply rename the dataset). Can someone show me how to better do this?

I have looked at some other questions that suggest using other things like lists but (of course without knowing too much about R) for the number of items in the column, it doesn't seem like a for loop would terrible, and I've had some trouble figuring out how to use lists anyway.

Upvotes: 1

Views: 395

Answers (1)

akrun
akrun

Reputation: 887158

We can use assign

for(i in unique_categories) {
      assign(i, regular_season %>%
            filter(category %in% i)
  }

Or another option is split and list2env

list2env(split(regular_season, regular_season$category), 
        .GlobalEnv)

Upvotes: 3

Related Questions