【问题标题】:How can I separate a list of lists in a dataframe?如何分隔数据框中的列表列表?
【发布时间】:2018-10-22 17:38:24
【问题描述】:

我正在使用 traintrips 分析数据框。数据格式如下:

 tripnumber stop       
<int> <list>     
1 <list [34]>
2 <list [34]>
3 <list [33]>
4 <list [20]>
5 <list [17]>
6 <list [17]>

每个行程编号都与一定数量的站点相关联,例如行程 1 有 34 个站点。

重要的一点是,停靠站列表不仅仅是车站列表,而是格式化为带有车站+信息的另一个列表(我们称之为车站列表),结构如下:

list(Station = "ams", Arival_time = "0135", Departure_time = "0138", Index = "1")

我想在第一个站列表的行程号之后的第一列中列出未列出的站列表列表,在第二列中第二个站列表等,使其如下所示:

 tripnumber stop1 stop2 stop3 stop4 stop5 .... 
<int> <list>     
1 <list [4]> <list [4]> <list [4]> <list [4]> <list [4]> ....
2 <list [4]> <list [4]> <list [4]> <list [4]> <list [4]> ....
3 <list [4]> <list [4]> <list [4]> <list [4]> <list [4]> ....
4 <list [4]> <list [4]> <list [4]> <list [4]> <list [4]> ....
5 <list [4]> <list [4]> <list [4]> <list [4]> <list [4]> ....
6 <list [4]> <list [4]> <list [4]> <list [4]> <list [4]> ....

我尝试使用purrr 库对其进行格式化。但是我对这个包不太熟悉,困难在于我不能在不丢失tripnumber结构或“stationlist”结构的情况下让它工作。

任何提示如何解决这个问题?

编辑:

  • 以下dput(head(traintrips)可以作为测试文件复制粘贴到R:.txt file
  • 如果停靠点列多于实际停靠点,则单元格应保持为空(“”)

【问题讨论】:

  • 您好,欢迎来到 SO!站点有名称吗?如果您能提供一些reproducible data,那将非常有帮助,因为这样可以更轻松地测试和验证解决方案。仅仅几行,每行停几站似乎就足够了。
  • 另外,对于行程 3,您希望在(例如)输出列 stop34 中拥有什么,即如何处理每次行程的不同停靠次数?
  • 我赞同@CalumYou 的评论,请至少包含dput(head(x))
  • 感谢@CalumYou,添加了一个测试文件,可以下载了
  • 查看tidyr::unnest()nest()

标签: r list purrr


【解决方案1】:

通过取消嵌套并使用以下代码重新调整结果来使其工作:

DFnew <- unnest(traintrips, traintrips$stop) 
DFnew$time <- with(DFnew, ave(tripnumber, tripnumber, FUN = seq_along)) # add time column
names(DFnew)[2] <- paste("stop") # to remove the dollar sign from the colname of the unnested data
DFnew <- spread(DFnew, time, stop)

结果:

> dim(DFnew)
[1]  6 35

> head(DFnew[,1:6])
# A tibble: 6 x 6
  tripnumber `1`        `2`        `3`        `4`        `5`       
       <int> <list>     <list>     <list>     <list>     <list>    
1          1 <list [4]> <list [4]> <list [4]> <list [4]> <list [4]>
2          2 <list [4]> <list [4]> <list [4]> <list [4]> <list [4]>
3          3 <list [4]> <list [4]> <list [4]> <list [4]> <list [4]>
4          4 <list [4]> <list [4]> <list [4]> <list [4]> <list [4]>
5          5 <list [4]> <list [4]> <list [4]> <list [4]> <list [4]>
6          6 <list [4]> <list [4]> <list [4]> <list [4]> <list [4]>

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多