【问题标题】:How to transform a particular column to row如何将特定列转换为行
【发布时间】:2018-07-14 06:22:47
【问题描述】:

我想将看起来像左表的数据重组到右表,我想将其转换为。

上面左表中的示例数据编码如下。

data <- data.frame(country=c('US', 'US', 'US', 'US', 'US', 'UO', 'UO', 'UO', 'UO', 'UO'),
               year=c(2015, 2015, 2016, 2016, 2016, 2015, 2015, 2015, 2016, 2016),
               region=c('NY', 'CA', 'MI', 'MA', 'IL', 'GH', 'FD', 'AH', 'PO', 'LQ'))

感谢您的建议。

【问题讨论】:

    标签: r dplyr reshape dcast


    【解决方案1】:

    使用 dplyr 和 purrr 包来解决这个问题

    #collection of many packagaes like tibble,dplyr,purrr,ggplot and etc.
    library(tidyverse) 
    data %>%
        #First two columns contain grouping variables
        group_by(year,country) %>%
        #based on grouping variables, make other columns into a list and store 
        #them in an other column
        nest() %>%
        #map is from purrr package, which can deal with list in a dataframe
        # t() transpose the dataframe, as.tibble() make them into tibble class
        mutate(data = map(data,~ as.tibble(t(.x)))) %>%
        #unnest the list column
        unnest() %>%
        #rename columns
        rename(region1 = V1, region2 = V2, region3 = V3)
    

    结果:

    # A tibble: 4 x 5
       year country region1 region2 region3
      <dbl> <fct>   <chr>   <chr>   <chr>  
    1  2015 US      NY      CA      NA     
    2  2016 US      MI      MA      IL     
    3  2015 UO      GH      FD      AH     
    4  2016 UO      PO      LQ      NA   
    

    如果需要,将 NA 替换为空字符串“”。


    或者这样重命名:

    library(stringr)
    colnames(temp) <- str_replace(colnames(temp),pattern = fixed("V"),replacement = "region")           
    colnames(temp)
    #result
    [1] "year"    "country" "region1" "region2" "region3"
    

    【讨论】:

    • 非常感谢Yifu Yan的帮助和优秀的代码。
    猜你喜欢
    • 1970-01-01
    • 2021-03-18
    • 2021-05-11
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多