【问题标题】:Having trouble using the 'gather' function in tidyr在 tidyr 中使用“收集”功能时遇到问题
【发布时间】:2020-02-28 12:51:20
【问题描述】:

我在使用 R 中的收集函数时遇到问题。 这是示例数据框 -

library(dplyr)
library(tidyr)
DF = data.frame(Region = c("Asia", "Asia", "Asia", "Europe", "Europe"),
                `Indicator Name` = c("Population", "GDP", "GNI", "Population", "GDP"),
                `2004` = c(22, 33,44,55,56),
                `2005` =c(223, 44,555,66,64))

Region Indicator.Name X2004 X2005
1   Asia     Population    22   223
2   Asia            GDP    33    44
3   Asia            GNI    44   555
4 Europe     Population    55    66
5 Europe            GDP    56    64

这就是我想要的数据框


DF2 = data.frame(Region = c("Asia", "Asia", "Europe", "Europe"),
                 Year =  c("X2004", "X2005"),
                 population = c(22, 224, 55, 66),
                 GDP = c(33, 44, 56,64))

Region  Year population GDP
1   Asia X2004         22  33
2   Asia X2005        224  44
3 Europe X2004         55  56
4 Europe X2005         66  64

我想通过tidyr 中的gather 函数来执行此操作。 我不知道该怎么做。这是我尝试过的 -

gather(DF, key= DF$Indicator.Name, values = "values")

【问题讨论】:

    标签: r dplyr plyr tidyr


    【解决方案1】:

    这不是一个简单的gather 函数。首先,您需要使数据框变长,然后将其变宽以切换所需的列。
    这是使用新的pivot_longer 和pivot_wider 函数的解决方案。

    library(dplyr)
    library(tidyr)
    
    DF = data.frame(Region = c("Asia", "Asia", "Asia", "Europe", "Europe"),
                    `Indicator Name` = c("Population", "GDP", "GNI", "Population", "GDP"),
                    `2004` = c(22, 33,44,55,56),
                    `2005` =c(223, 44,555,66,64))
    
    
    
    DF %>% pivot_longer(cols = starts_with("x")) %>% 
           pivot_wider(names_from = Indicator.Name, values_from = value) 
    
    # A tibble: 4 x 5
    Region name  Population   GDP   GNI
    <fct>  <chr>      <dbl> <dbl> <dbl>
    1 Asia   X2004         22    33    44
    2 Asia   X2005        223    44   555
    3 Europe X2004         55    56    NA
    4 Europe X2005         66    64    NA
    

    【讨论】:

    • 我很想使用 pivot_longer 函数,但他们还没有在 tidyr 的 CRAN 更新中发布它。从 devtools 安装时遇到问题 - 只能等到它在 CRAN 上发布。
    • pivot_longer 是 2019 年 9 月 1 日在 CRAN 上发布的 tidyr 1.0.0 的一部分。cran.r-project.org/web/packages/tidyr/index.html
    【解决方案2】:

    使用gather 和spread,您有:

    DF %>% 
      gather(-Indicator.Name, -Region, key= "Year", value = "value") %>%
      spread(Indicator.Name, value)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-04
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多