0

I would like to transpose the data from my variable columns to rows.

My data looks like this:

State    Republicans   Democrats  Others

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

I want it to look like this:

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
Henry Ecker
  • 31,792
  • 14
  • 29
  • 50
Clara
  • 91
  • 3

1 Answers1

0

One option is to use pivot_longer from dplyr.

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
www
  • 37,164
  • 12
  • 37
  • 72