Reputation: 181
Is there a way to split a dataframe into groups of elements and not individual elements. For example, in the following code
rs_scq_user_ <- split(regular_season, list(regular_season$season,
regular_season$category, regular_season$question))
Say within the "season" column, I wanted
winter, spring
to stay together and
summer, fall
to stay together. How would I go about doing this?
Upvotes: 2
Views: 127
Reputation: 886938
An option is to create a logical column for that. Below, the 'flag' with TRUE
values indicate 'winter', 'spring' and the FALSE
would be automatically the res i.e. 'summer', fall' (assuming there are only 4 season in the data)
regular_season$flag <- with(regular_season, season %in%
c('winter', 'spring'))
Then, use split
with 'category', 'question' and 'flag' instead of 'season'
lst1 <- split(regular_season, regular_season[c('category', 'question',
'flag')], drop = TRUE)
Or another option is group_split
from dplyr
library(dplyr)
regular_season %>%
group_split(category, question, flag = season %in% c('winter', 'spring'))
Or if we prefer to have a concatenated 'season' as new 'season'
regular_season %>%
group_split(category, question,
season_concat = case_when(season %in% c('winter', 'spring')
~ 'winter_spring', TRUE ~ 'summer_fall'))
Upvotes: 2