【发布时间】:2018-09-20 01:24:06
【问题描述】:
我正在尝试将一个宽数据集转换为一个长而整洁的数据集。我经常使用tidyr::gather() 函数来处理这类任务,只是现在我有一个非常奇怪的数据集。
以下是我的一个小版本。正如您可以想象的那样,后面带有__1 的列会重复直到编号__16 或我的真实数据框中的某些内容。这可以用tidyr 或dplyr 工具解决吗?
# A tibble: 1 x 10
code city party_short party_long votes seats party_short__1 party_long__1 votes__1 seats__1
<dbl> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr> <dbl> <dbl>
1 3630 Amsterdam PVDA Partij van de Arbeid 1833 5.00 HARLBEL Harlinger Belang 942 2.00
为了重现性:
library(tidyverse)
df <- tibble(code = 3630,
city = "Amsterdam",
party_short = "PVDA",
party_long = "Partij van de Arbeid",
votes = 1833,
seats = 5,
party_short__1 = "HARLBEL",
party_long__1 = "Harlinger Belang",
votes__1 = 942,
seats__1 = 2)
具有所需的输出:
# A tibble: 2 x 6
code city party_short party_long votes seats
<dbl> <chr> <chr> <chr> <dbl> <dbl>
1 3630 Amsterdam PVDA Partij van de Arbeid 1833 5.00
2 3630 Amsterdam HARLBEL Harlinger Belang 942 2.00
【问题讨论】:
-
只是为了确定;
code和city列没有其他带有__#的列? (即code和city在所需输出中的所有行保持相同) -
是的,只有
party_short、party_long、votes和seats重复(当然值不同)
标签: r transpose tidyr data-munging