【问题标题】:Transpose table from column to rows (R)? [duplicate]将表从列转置到行(R)? [复制]
【发布时间】:2021-11-14 03:34:43
【问题描述】:

我想将变量列中的数据转换为行。

我的数据如下所示:

State    Republicans   Democrats  Others

NY         20             40        5
CA         30             40        5  
LA         20             50        5

我希望它看起来像这样:

State    Party           Votes

NY       Democrats       40
NY       Republicans     20
NY       Others           5
CA       Democrats       40
CA       Republicans     30
CA       Others           5
LA       Democrats       50
LA       Republicans     20
LA       Others           5

【问题讨论】:

    标签: r pivot pivot-table


    【解决方案1】:

    一种选择是使用来自dplyrpivot_longer

    library(dplyr)
    library(tidyr)
    
    dat2 <- dat %>%
      pivot_longer(-State, names_to = "Party", values_to = "Votes")
    dat2
    # # A tibble: 9 x 3
    #   State Party       Votes
    #   <chr> <chr>       <int>
    # 1 NY    Republicans    20
    # 2 NY    Democrats      40
    # 3 NY    Others          5
    # 4 CA    Republicans    30
    # 5 CA    Democrats      40
    # 6 CA    Others          5
    # 7 LA    Republicans    20
    # 8 LA    Democrats      50
    # 9 LA    Others          5
    

    【讨论】:

      猜你喜欢
      • 2013-07-27
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      相关资源
      最近更新 更多