Home > Software engineering >  how to create nested data frame by collapsing columns
how to create nested data frame by collapsing columns

Time:10-13

I have a dataframe I want to collapse some columns (y and z) to create a nested dataframe, for instance:

df <- data.frame(x = rep(c(1,2,3,4),times=3), y = rep(c("Y","W","T","R"),times=3), z = rep(c("A","B","C","D"),times=3))

x   y   z
=========
1   Y   A       
2   W   B       
3   T   C       
4   R   D       
1   Y   A       
2   W   B       
3   T   C       
4   R   D       
1   Y   A       
2   W   B

I want to collapse the z column and nest it for each unique group of x. The resulting dataframe should look like this:

x   zy
======
1   <dataframe>         
2   <dataframe>         
3   <dataframe>     
4   <dataframe>

How do I accomplish this?

CodePudding user response:

library(tidyverse)

df %>% 
  group_by(x) %>% 
  nest(data = c(z, y))

# A tibble: 4 × 2
# Groups:   x [4]
      x data            
  <dbl> <list>          
1     1 <tibble [3 × 2]>
2     2 <tibble [3 × 2]>
3     3 <tibble [3 × 2]>
4     4 <tibble [3 × 2]>

CodePudding user response:

Try a list

library(dplyr)

df %>% 
  group_by(x) %>% 
  summarise(zy = list(cbind(y, z)))
# A tibble: 4 × 2
      x zy
  <dbl> <list>
1     1 <chr [3 × 2]>
2     2 <chr [3 × 2]>
3     3 <chr [3 × 2]>
4     4 <chr [3 × 2]>
  •  Tags:  
  • r
  • Related