Removing nested data frame structure after unnesting data frames

Viewed 188

After unnesting a list of data.frames columns using unnest_longer, the columns from the unnested data frame seem to retain some sort of data frame structure.

    library(tidyverse)
    
    # data
    d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))
    d2 <- data.frame(y1 = c(3, 2, 1), y2 = c(6, 5, 4))
    my_df <- tibble(some_data = list(d1, d2), id = c("d1", "d2"))
    
    # Unnesting
    result <- my_df %>%
      unnest_longer(some_data)
    
    names(result) # expecting "y1", "y2", "id" 

I would expect the column names to be "y1, "y2" and "id" not "some_data" and "id". Removing this data structure would quicker analysis on the tibble using dplyr (e.g., selecting, grouping)

Same as this question here

1 Answers

We can use unnest

library(dplyr)
library(tidyr)
my_df %>%
   unnest(c(some_data))

-output

# A tibble: 6 x 3
#     y1    y2 id   
#  <dbl> <dbl> <chr>
#1     1     4 d1   
#2     2     5 d1   
#3     3     6 d1   
#4     3     6 d2   
#5     2     5 d2   
#6     1     4 d2   
Related