如何在R中的小标题中将列表列转换为向量

时间:2019-02-28 19:52:17

标签: r dataframe tibble

我正在尝试折叠下面的小标题(称为数据)中的Weeks列,以便结果是包含两列的小标题:1表示星期,另一栏表示关联的值。由于周列是一个列表,因此我不确定该如何做。你能帮忙吗?

> head(data)
# A tibble: 6 x 1
  ``$Weeks   $Value
  <list>      <dbl>
1 <date [9]>     30
2 <date [3]>     20
3 <date [3]>     15
4 <date [5]>     10
5 <date [2]>      9
6 <date [9]>      5

所需结果如下:

      $Weeks   $Value
      <Date>      <dbl>
 1  "2019-01-01     30
 2  "2019-01-08     30
 3  "2019-01-15     30
 etc..

当前结构:

  > str(data)
List of 1
 $ :Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   7 obs. of  2 variables:
  ..$ Weeks:List of 7
  .. ..$ : Date[1:9], format: "2018-11-11" "2018-11-18" "2018-11-25" "2018-12-02" ...
  .. ..$ : Date[1:3], format: "2018-12-02" "2018-12-09" "2018-12-16"
  .. ..$ : Date[1:3], format: "2018-12-23" "2018-12-30" "2019-01-06"
  .. ..$ : Date[1:5], format: "2018-11-04" "2018-11-11" "2018-11-18" "2018-11-25" ...
  .. ..$ : Date[1:2], format: "2018-11-25" "2018-12-02"
  .. ..$ : Date[1:9], format: "2018-11-18" "2018-11-25" "2018-12-02" "2018-12-09" ...
  .. ..$ : Date[1:14], format: "2018-09-30" "2018-10-07" "2018-10-14" "2018-10-21" ...
  ..$ Value: num [1:7] 30 20 15 10 9 5 6

dput(数据)

> dput(data)
list(structure(list(Weeks = list(structure(c(17846, 17853, 17860, 
17867, 17874, 17881, 17888, 17895, 17902), class = "Date"), structure(c(17867, 
17874, 17881), class = "Date"), structure(c(17888, 17895, 17902
), class = "Date"), structure(c(17839, 17846, 17853, 17860, 17867
), class = "Date"), structure(c(17860, 17867), class = "Date"), 
    structure(c(17853, 17860, 17867, 17874, 17881, 17888, 17895, 
    17902, 17909), class = "Date"), structure(c(17804, 17811, 
    17818, 17825, 17832, 17839, 17846, 17853, 17860, 17867, 17874, 
    17881, 17888, 17895), class = "Date")), Value = c(30, 20, 
15, 10, 9, 5, 6)), row.names = c(NA, -7L), class = c("tbl_df", 
"tbl", "data.frame")))

1 个答案:

答案 0 :(得分:1)

修改后的答案

好的,因此您的原始数据存储为列表,这使得unnest()函数无法正常运行。我们需要先提取元素。然后,由于您的列表列本身就是列表的列表,因此我们必须使用map提取我们想要的内容。 下面的解决方案可以解决此问题,并为您提供所需的内容。

  > data[[1]] %>%
      mutate(Weeks = map(Weeks, ~ tibble(Weeks =.x))) %>%
      unnest()

输出:

  # A tibble: 45 x 2
    Value Weeks     
    <dbl> <date>    
  1    30 2018-11-11
  2    30 2018-11-18
  3    30 2018-11-25
  4    30 2018-12-02
  5    30 2018-12-09
  6    30 2018-12-16
  7    30 2018-12-23
  8    30 2018-12-30
  9    30 2019-01-06
 10    20 2018-12-02

原始答案:

正如akrun在评论中所说,您可以执行unnest(data, Weeks)