Reputation: 4407
Hi i have encountered an issue after using group_by
and nest
when i try to transform the result to a full dataframe. Specifically, the data looks something like the example with columns being in the format of both character
and list
library(tibble)
example = as_tibble(data.frame(dim_1 = c('a','b'),
dim_2 = c('g', 'k')))
l <- as.list(data.frame(ds = seq(1,10, by =1), result = seq(100,1000,by=100)))
example$result = l
The result I want is something like this
ideal_result = cbind(data.frame(dim_1 = rep('a',10), dim_2 = rep('g',10)),data.frame(ds = seq(1,10, by =1), result = seq(100,1000,by=100)))
Thank you!
Upvotes: 0
Views: 199
Reputation: 34511
You can use tidyr::expand_grid()
:
library(tidyr)
library(tibble)
library(dplyr)
expand_grid(example[1:2], as_tibble(example$result))
# A tibble: 20 x 4
dim_1 dim_2 ds result
<chr> <chr> <dbl> <dbl>
1 a g 1 100
2 a g 2 200
3 a g 3 300
4 a g 4 400
5 a g 5 500
6 a g 6 600
7 a g 7 700
8 a g 8 800
9 a g 9 900
10 a g 10 1000
11 b k 1 100
12 b k 2 200
13 b k 3 300
14 b k 4 400
15 b k 5 500
16 b k 6 600
17 b k 7 700
18 b k 8 800
19 b k 9 900
20 b k 10 1000
Or convert result
into a tibble and unnest.
example %>%
mutate(result = list(as_tibble(result))) %>%
unnest(result)
Upvotes: 1
Reputation: 8880
library(tidyverse)
example = as_tibble(data.frame(dim_1 = c('a','b'),
dim_2 = c('g', 'k')))
l <- as.list(data.frame(ds = seq(1,10, by =1), result = seq(100,1000,by=100)))
example$result = l
map_dfc(example$result, ~.x) %>%
chop(c(ds, result)) %>%
bind_cols(example[1:2]) %>%
unnest(c(ds, result))
#> # A tibble: 20 x 4
#> ds result dim_1 dim_2
#> <dbl> <dbl> <chr> <chr>
#> 1 1 100 a g
#> 2 2 200 a g
#> 3 3 300 a g
#> 4 4 400 a g
#> 5 5 500 a g
#> 6 6 600 a g
#> 7 7 700 a g
#> 8 8 800 a g
#> 9 9 900 a g
#> 10 10 1000 a g
#> 11 1 100 b k
#> 12 2 200 b k
#> 13 3 300 b k
#> 14 4 400 b k
#> 15 5 500 b k
#> 16 6 600 b k
#> 17 7 700 b k
#> 18 8 800 b k
#> 19 9 900 b k
#> 20 10 1000 b k
Created on 2022-01-25 by the reprex package (v2.0.1)
Upvotes: 0