Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify dataframe based on the unique levels of column and then combine values from 2 other columns inside them

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

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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%
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading