从长到宽的数据 - 每 N 行
Long to Wide Data - Every Nth row
我正在编写一个新脚本,我从网站上提取(使用 rvest
)html table。数据格式一致,但值每天都在变化。
当 table 被抓取时,它是长格式的。虽然数据可以在逻辑上进行分组,但我想将数据从长格式转换为宽格式。每个新变量之间有 15 行......是否有一个函数,或者使用诸如 tidyr
/reshape2
之类的包可以用来达到预期的结果?
快速示例,仅考虑列表中的 1 个变量:
A.1
A
Name A
-1
0
18:05
00:00
0:50
2
(no value presented, will replace with 0 in my code later on)
(no value presented, will replace with 0 in my code later on)
1
1
4
13
想要的结果:
A.1 A Name A -1 0 18:05 00:00 0:50 2 0 0 1 1 4 13
它会重复大约 1000-1200 行,我每天都会 运行 这个代码。
提前致谢!
根据您的数据框,
df = data.frame(c("A.1", "A", "Name A", -1, 0, "18:05", "00:00", "0:50", 2, NA, NA, 1, 1, 4, 13,
"B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "B10", "B11", "B12", "B13", "B14", "B15"), stringsAsFactors=FALSE)
你可以按如下方式在一行中完成(不需要任何包):
View(t(as.data.frame(split(df, (as.numeric(rownames(df))-1) %/% 15))))
从这里您需要继续...根据您的喜好替换 NA
并修改数据类型等。
我正在编写一个新脚本,我从网站上提取(使用 rvest
)html table。数据格式一致,但值每天都在变化。
当 table 被抓取时,它是长格式的。虽然数据可以在逻辑上进行分组,但我想将数据从长格式转换为宽格式。每个新变量之间有 15 行......是否有一个函数,或者使用诸如 tidyr
/reshape2
之类的包可以用来达到预期的结果?
快速示例,仅考虑列表中的 1 个变量:
A.1
A
Name A
-1
0
18:05
00:00
0:50
2
(no value presented, will replace with 0 in my code later on)
(no value presented, will replace with 0 in my code later on)
1
1
4
13
想要的结果:
A.1 A Name A -1 0 18:05 00:00 0:50 2 0 0 1 1 4 13
它会重复大约 1000-1200 行,我每天都会 运行 这个代码。
提前致谢!
根据您的数据框,
df = data.frame(c("A.1", "A", "Name A", -1, 0, "18:05", "00:00", "0:50", 2, NA, NA, 1, 1, 4, 13,
"B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "B10", "B11", "B12", "B13", "B14", "B15"), stringsAsFactors=FALSE)
你可以按如下方式在一行中完成(不需要任何包):
View(t(as.data.frame(split(df, (as.numeric(rownames(df))-1) %/% 15))))
从这里您需要继续...根据您的喜好替换 NA
并修改数据类型等。