将 table 从列转置到行 (R)?

Transpose table from column to rows (R)?

我想将数据从可变列转置到行。

我的数据是这样的:

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

一种选择是使用 dplyr 中的 pivot_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