如何将字符列和列表列转换为 R 中的数据框

How to transform a character column and a list column to a dataframe in R

您好,当我尝试将结果转换为完整数据帧时,使用 group_bynest 后遇到了问题。具体来说,数据看起来类似于示例,列的格式为 characterlist

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

我想要的结果是这样的

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)))

谢谢!

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

reprex package (v2.0.1)

于 2022-01-25 创建

您可以使用 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

或者将result转换为tibble和unnest。

example %>%
  mutate(result = list(as_tibble(result))) %>%
  unnest(result)