首页 > 解决方案 > 在R中将行组合到数据框

问题描述

我有一些这种格式的数据,我想在 R 中导入,到目前为止,我使用 read.csv 来读取它们,但每一块都以自己的行结束。

18.07.19
05:41:05
Information
18.07.19
05:43:48
Something
18.07.19
05:20:48
Text
18.07.19
01:16:45

到目前为止很好,但我需要它是这种格式:

18.07.19    05:41:05    Information
18.07.19    05:43:48    Something   
18.07.19    05:20:48    Text    
18.07.19    01:16:45

因为我想将数据用作数据框。

我认为 dcast 可能是正确的方法,但我无法弄清楚我必须作为参数传递什么。

标签: rdataframe

解决方案


这是一个黑客,data.table::dcast因为你提到过:

x <- read.csv(header=FALSE, stringsAsFactors=FALSE, text="
18.07.19
05:41:05
Information
18.07.19
05:43:48
Something
18.07.19
05:20:48
Text
18.07.19
01:16:45")

x$i <- head(rep(1:3, times=ceiling(nrow(x) / 3)), n = nrow(x))
x$j <- head(rep(1:ceiling(nrow(x)), each=3), n = nrow(x))

data.table::dcast(x, j ~ i, value.var="V1")
#   j        1        2           3
# 1 1 18.07.19 05:41:05 Information
# 2 2 18.07.19 05:43:48   Something
# 3 3 18.07.19 05:20:48        Text
# 4 4 18.07.19 01:16:45        <NA>

(您可以轻松删除j和重命名列名。)


推荐阅读