In R, how to transform Tibble into dataframe

Asked

Viewed 436 times

2

I have a Tibble structure resulting from the following script, using the purrr package:

data %>% group_by(REGIAO , V1023) %>% nest() %>% mutate( teste = map(data, ff))

Where ff is a particular function that I created to apply in each REGIAO and V1023 group. The result is basically similar to this

    # A tibble: 18 x 3
         REGIAO V1023                teste
          <chr> <int>               <list>
 1        Norte     1 <data.frame [3 x 6]>
 2        Norte     4 <data.frame [3 x 6]>
 3        Norte     2 <data.frame [3 x 6]>
 4     Nordeste     4 <data.frame [3 x 6]>
 5     Nordeste     1 <data.frame [3 x 6]>
 6     Nordeste     2 <data.frame [3 x 6]>
 7     Nordeste     3 <data.frame [3 x 6]>
 8      Sudeste     4 <data.frame [3 x 6]>
 9      Sudeste     1 <data.frame [3 x 6]>
10      Sudeste     2 <data.frame [3 x 6]>
11      Sudeste     3 <data.frame [3 x 6]>
12          Sul     2 <data.frame [3 x 6]>
13          Sul     4 <data.frame [3 x 6]>
14          Sul     1 <data.frame [3 x 6]>
15 Centro-Oeste     4 <data.frame [3 x 6]>
16 Centro-Oeste     1 <data.frame [3 x 6]>
17 Centro-Oeste     2 <data.frame [3 x 6]>
18 Centro-Oeste     3 <data.frame [3 x 6]>

The "column" test consists of dataframes that have the same variables both in their rows and in their columns. That is, it has the same dimensions, as we can see above. I want to turn this into dataframe. That is, I want to stack each dataframe of the variable test, but without losing its REGIAO and neither the variable V1023. Some solution?

  • You can edit the question with the result of dput(head(data2)) where data2 that’s the one tibble?

1 answer

3


Use the function unnest of tidyr:

Example:

> library(dplyr)
> library(purrr)
> library(tidyr)
> 
> df <- tibble(x = 1:10, y = 1:10) %>%
+   mutate(z = map2(x, y, ~data.frame(a = .x + 1:5, b = .y + 1:5)))
> 
> print(df)
# A tibble: 10 x 3
       x     y                    z
   <int> <int>               <list>
 1     1     1 <data.frame [5 x 2]>
 2     2     2 <data.frame [5 x 2]>
 3     3     3 <data.frame [5 x 2]>
 4     4     4 <data.frame [5 x 2]>
 5     5     5 <data.frame [5 x 2]>
 6     6     6 <data.frame [5 x 2]>
 7     7     7 <data.frame [5 x 2]>
 8     8     8 <data.frame [5 x 2]>
 9     9     9 <data.frame [5 x 2]>
10    10    10 <data.frame [5 x 2]>
> 
> df %>% unnest(z)
# A tibble: 50 x 4
       x     y     a     b
   <int> <int> <int> <int>
 1     1     1     2     2
 2     1     1     3     3
 3     1     1     4     4
 4     1     1     5     5
 5     1     1     6     6
 6     2     2     3     3
 7     2     2     4     4
 8     2     2     5     5
 9     2     2     6     6
10     2     2     7     7
# ... with 40 more rows

Browser other questions tagged

You are not signed in. Login or sign up in order to post.