I have the dataframe below and I want to modify it in a way that will have 3 columns Election,Party_1 and Party_2 and inside Party columns a paste between Candidate and Voteshare
df<-structure(list(ELECtion = c("PC_2009", "AC_2011", "PC_2014",
"AC_2016", "PC_2019", "AC_2021", "PC_2009", "AC_2011", "PC_2014",
"AC_2016", "PC_2019", "AC_2021"), Party = c("Party_1", "Party_1",
"Party_1", "Party_1", "Party_1", "Party_1", "Party_2", "Party_2",
"Party_2", "Party_2", "Party_2", "Party_2"), Candidate = c("Mr.Sen",
"Dr.Kar", "Mr. Sen", "Dr.Kar", "Dr.Reddy", "Dr.Kar", "Dr.Dutta",
"Mrs.Dondopani", "Mr. Das", "Mrs.Dondopani", "Mr,Das", "Mrs.Dondopani"
), Voteshare = c(0.2, 0.32, 0.12, 0.36, 0.005, 0.26, 0.15, 0.23,
0.45, 0.28, 0.54, 0.38)), row.names = c(NA, -12L), class = c("tbl_df",
"tbl", "data.frame"))
like
>Solution :
With paste + pivot_wider:
library(tidyr)
library(dplyr)
df %>%
mutate(cand_vote = paste(Candidate, paste0(Voteshare * 100, "%")), .keep = "unused") %>%
pivot_wider(names_from = "Party", values_from = "cand_vote")
# ELECtion Party_1 Party_2
# <chr> <chr> <chr>
# 1 PC_2009 Mr.Sen 20% Dr.Dutta 15%
# 2 AC_2011 Dr.Kar 32% Mrs.Dondopani 23%
# 3 PC_2014 Mr. Sen 12% Mr. Das 45%
# 4 AC_2016 Dr.Kar 36% Mrs.Dondopani 28%
# 5 PC_2019 Dr.Reddy 0.5% Mr,Das 54%
# 6 AC_2021 Dr.Kar 26% Mrs.Dondopani 38%
