用tidyr将两行分散到一行

时间:2018-03-21 14:43:00

标签: r transpose tidyr

我已经看过thisthisthis但仍然不知道如何在tidyr::spread()函数中解决以下问题。< / p>

这是我的示例数据框:

libary(tidyverse)

df <- structure(list(Jaar = c(2014L, 2018L), Gemeente = c("Stichtse Vecht", 
"Stichtse Vecht"), GMcode = c("GM1904", "GM1904"), Partij = c("VVD", 
"VVD"), Aantal_stemmen = c(4347L, 0L)), .Names = c("Jaar", "Gemeente", 
"GMcode", "Partij", "Aantal_stemmen"), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"))

结果:

# A tibble: 2 x 5
   Jaar Gemeente       GMcode Partij Aantal_stemmen
  <int> <chr>          <chr>  <chr>           <int>
1  2014 Stichtse Vecht GM1904 VVD              4347
2  2018 Stichtse Vecht GM1904 VVD                 0

当我运行以下代码时,我没有得到所需的一行,但是有两张NA&#39;

df %>%
  rowid_to_column() %>% # Without this in my original dataframe I'll get an error: Error: Duplicate identifiers for rows 
  spread(Jaar, Aantal_stemmen)

结果:

# A tibble: 5,938 x 6
   rowid Gemeente       GMcode Partij   `2014` `2018`
   <int> <chr>          <chr>  <chr>     <int>  <int>
 1     1 Stichtse Vecht GM1904 VVD        4347     NA
 2     2 Stichtse Vecht GM1904 VVD          NA      0

1 个答案:

答案 0 :(得分:2)

我不确定你想要什么,因为你没有提供想要的输出。我希望以下内容对您有所帮助。

rowid_to_column的调用会生成一个包含2行的列。这就是它打算做的事情。删除它可以解决您的问题:

df %>%
  # rowid_to_column() %>%
  spread(Jaar, Aantal_stemmen)

给出了

# A tibble: 1 x 5
  Gemeente       GMcode Partij `2014` `2018`
  <chr>          <chr>  <chr>   <int>  <int>
1 Stichtse Vecht GM1904 VVD      4347      0

请告诉我这是否是你想要的。

相关问题