Home > Enterprise >  Splitting panel data rows
Splitting panel data rows

Time:06-28

I have a dataset that has rows I would like to split. Is there a simple way to do this?

data = data.frame(id = 111, t1 = 277,t2 = 385, meds = 1)

I am trying to use a conditional to allow me to split rows and create an output similar to this data

data = data.frame(id = 111, t1 = c(277,366),t2 = c(365,385), meds = 1)

Any advice would help thanks

CodePudding user response:

I think you can just do a little row-wise summary using dplyr

library(dplyr)

data %>%
  rowwise() %>%
  summarize(id, 
            t1 = if(t1 < 365 & t2 > 365) c(t1, 366) else t1,
            t2 = if(t1 < 365 & t2 > 365) c(365, t2) else t2,
            meds)
#> # A tibble: 2 x 4
#>      id    t1    t2  meds
#>   <dbl> <dbl> <dbl> <dbl>
#> 1   111   277   365     1
#> 2   111   366   385     1

CodePudding user response:

I used group_split function from dplyr:

## Loading the required libraries
library(dplyr)
library(tidyverse)

## Creating the dataframe
df <- data.frame(
  t1= c(1:600),
  t2= c(200:799)
)  

## Conditional Column
df1 = df %>%
  mutate(DataframeNo = ifelse(t1<365 & t2>365, "2 dfs","1 df" )) %>%
  group_by(DataframeNo)
  
## Get the first Dataframe
group_split(df1)[[1]]

## Get the second Dataframe
group_split(df1)[[2]]

Output

> group_split(df1)[[1]]
# A tibble: 402 x 3
      t1    t2 DataframeNo
   <int> <int> <chr>      
 1     1   200 1 df       
 2     2   201 1 df       
 3     3   202 1 df       
 4     4   203 1 df       
 5     5   204 1 df       
 6     6   205 1 df       
 7     7   206 1 df       
 8     8   207 1 df       
 9     9   208 1 df       
10    10   209 1 df       
# ... with 392 more rows
> ## Get the second Dataframe
> group_split(df1)[[2]]
# A tibble: 198 x 3
      t1    t2 DataframeNo
   <int> <int> <chr>      
 1   167   366 2 dfs      
 2   168   367 2 dfs      
 3   169   368 2 dfs      
 4   170   369 2 dfs      
 5   171   370 2 dfs      
 6   172   371 2 dfs      
 7   173   372 2 dfs      
 8   174   373 2 dfs      
 9   175   374 2 dfs      
10   176   375 2 dfs      
# ... with 188 more rows
  • Related