Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group dataframe by ID and then split it into multiple dataframes for each group [duplicate]

Tags:

r

dplyr

Let's say I have a timeseries dataset with different IDs. Each ID has different values. I would like to first group the data by IDs. Then I would split this dataframe into Multiple dataframes for each group.

How can I do this in R using dplyr?

# Sample Data

ID = c("A", "B", "C", "A", "B", "C", "A", "B", "C")
Date = c("01/01/2022", "01/02/2022", "01/03/2022", "01/01/2022", "01/02/2022", "01/03/2022", "01/01/2022", "01/02/2022", "01/03/2022")
Value = c("45", "24", "33", "65", "24", "87", "51", "32", "72")

What I want:

df1

       ID       Date   Value
    1  A 01/01/2022    45
    2  A 01/02/2022    65
    3  A 01/03/2022    51
df2

       ID       Date   Value
    1  B 01/01/2022    24
    2  B 01/02/2022    24
    3  B 01/03/2022    32
df3

       ID       Date   Value
    1  C 01/01/2022    33
    2  C 01/02/2022    87
    3  C 01/03/2022    72



library(dplyr)

df = (ID, Date, Value)

    # What I tried so far
    
    df_group =  df  %>% 
      group_by(ID, Value) %>% 
      group_split() 
like image 980
Ed_Gravy Avatar asked Oct 24 '25 17:10

Ed_Gravy


1 Answers

Per answer, you want to set up your df as

df <- data.frame(ID, Date, Value)

You can then run the group_split

dataframe <- df %>%
group_split(ID)
like image 183
Brian Syzdek Avatar answered Oct 27 '25 05:10

Brian Syzdek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!