如何将一列静态文本插入到 r 中的嵌套数据框中?

How do I insert a column of static text into a nested dataframe in r?

对于专业人士来说这可能是一项微不足道的任务,但还无法弄清楚如何将“Slug”列中找到的文本插入到与 slug 关联的三个嵌套表中的每一个中。

![数据] (https://i.stack.imgur.com/YClrE.png)

我只是想将 Slug 值插入到嵌套表中并为每一行重复,以便我可以正确组合并跟踪关联。

欢迎任何提示!谢谢

解决方案

您可以将 rowwise()mutate(across())

一起使用
df %>%
  rowwise() %>% 
  mutate(across(floor_price_array:holder_hist, ~list(mutate(.x,slug=slug))))

说明

如果你的原始数据,比如 df,看起来像这样:

  id    slug  floor_price_array num_listed_hist   holder_hist      
  <chr> <chr> <list>            <list>            <list>           
1 a     hyznu <tibble [10 x 3]> <tibble [10 x 3]> <tibble [10 x 3]>
2 b     awxeb <tibble [10 x 3]> <tibble [10 x 3]> <tibble [10 x 3]>
3 c     pbncj <tibble [10 x 3]> <tibble [10 x 3]> <tibble [10 x 3]>

然后,上面的代码会将 slug 列中的值添加为每个嵌套 tibbles 中的新常量列,结果是(注意现在每个都有四列):

  id    slug  floor_price_array num_listed_hist   holder_hist      
  <chr> <chr> <list>            <list>            <list>           
1 a     hyznu <tibble [10 x 4]> <tibble [10 x 4]> <tibble [10 x 4]>
2 b     awxeb <tibble [10 x 4]> <tibble [10 x 4]> <tibble [10 x 4]>
3 c     pbncj <tibble [10 x 4]> <tibble [10 x 4]> <tibble [10 x 4]>

例如,floor_price_array,现在包含:

[[1]]
# A tibble: 10 x 4
        x      y      z slug 
    <dbl>  <dbl>  <dbl> <chr>
 1  1.44   2.02  -0.272 hyznu
 2 -0.598 -0.723 -0.528 hyznu
 3  0.490 -0.576 -1.62  hyznu
 4 -0.145  0.349  0.341 hyznu
 5 -0.362  0.503  0.584 hyznu
 6 -0.798 -0.839 -0.352 hyznu
 7 -0.503 -1.27  -1.18  hyznu
 8 -0.916 -0.654  0.335 hyznu
 9  0.578  0.137 -0.590 hyznu
10 -0.194 -0.674  1.73  hyznu

[[2]]
# A tibble: 10 x 4
         x        y       z slug 
     <dbl>    <dbl>   <dbl> <chr>
 1  0.876   0.665   -0.723  awxeb
 2 -0.0442 -0.00906  0.0829 awxeb
 3 -2.15    1.33     0.0692 awxeb
 4  0.264   0.237   -0.497  awxeb
 5  0.0381  0.0502  -1.58   awxeb
 6 -0.802   0.783   -1.34   awxeb
 7 -0.940   1.50    -0.542  awxeb
 8  0.209  -1.06     0.853  awxeb
 9  0.569  -1.15    -0.347  awxeb
10 -1.57   -0.0774   0.0250 awxeb

[[3]]
# A tibble: 10 x 4
          x       y       z slug 
      <dbl>   <dbl>   <dbl> <chr>
 1 -0.0289  -1.63    1.29   pbncj
 2 -0.716    0.647   0.0230 pbncj
 3 -0.0797  -0.0227  2.12   pbncj
 4 -0.358   -1.43   -1.81   pbncj
 5 -1.35    -0.402  -0.463  pbncj
 6 -0.00494 -0.136   1.50   pbncj
 7  1.09     0.124  -0.974  pbncj
 8 -1.18     1.78   -0.836  pbncj
 9  0.896   -1.38    0.199  pbncj
10  0.293    0.420   0.562  pbncj

输入数据:

df <- tibble(id = letters[1:3]
) %>%  
  rowwise() %>% 
  mutate(slug = paste0(sample(letters,5), collapse="")) %>% 
  mutate(floor_price_array=list(tibble(x=rnorm(10), y=rnorm(10), z=rnorm(10))),
         num_listed_hist=list(tibble(x=rnorm(10), y=rnorm(10), z=rnorm(10))),
         holder_hist=list(tibble(x=rnorm(10), y=rnorm(10), z=rnorm(10)))
         ) %>% ungroup()