Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Merge information from 2 columns together

Tags:

r

dplyr

I have created an example dataframe which has 3 different groups with 2 columns for each group.

Group_1 shows the total amount of participants and Group_1_Pos shows how many of the total participants are positive, etc:

df1 <- structure(list(Date = c("2016", "2017", "2018", "2019"), 
                       Group_1 = c("100", "200", "300", "400"), 
                       Group_1_Pos = c("10", "20", "30", "40"),
                       Group_2 = c("500", "600", "700", "800"),
                       Group_2_Pos = c("50", "60", "70", "80"), 
                       Group_3 = c("900", "1000", "1100", "1200"),
                       Group_3_Pos = c("90", "100", "110", "120")), 
                  class = "data.frame", row.names=c("1", "2", "3", "4"))
> df1
  Date Group_1 Group_1_Pos Group_2 Group_2_Pos Group_3 Group_3_Pos
1 2016     100          10     500          50     900          90
2 2017     200          20     600          60    1000         100
3 2018     300          30     700          70    1100         110
4 2019     400          40     800          80    1200         120

I would like to combine the total participant columns together with the positive participant columns in a way that keeps both values still seperated with brackets. As an example:

  Date      Group_1    Group_2     Group_3 
1 2016     100 (10)    500 (50)    900 (90)          
2 2017     200 (20)    600 (60)  1000 (100)        
3 2018     300 (30)    700 (70)  1100 (110)       
4 2019     400 (40)    800 (80)  1200 (120)        

So in this example I add the positive participants in () brackets next to the total participants and only keep 3 columns for the 3 groups.

Any help would be appreciated.

like image 833
Kak Schoen Avatar asked Nov 22 '25 02:11

Kak Schoen


1 Answers

Using dplyr you could go for something like:

library(dplyr)

df1 %>%
  mutate(Group_1 = paste0(Group_1, " (", Group_1_Pos, ")"),
         Group_2 = paste0(Group_2, " (", Group_2_Pos, ")"),
         Group_3 = paste0(Group_3, " (", Group_3_Pos, ")"),) %>% 
  select(-contains("Pos"))

#   Date  Group_1  Group_2    Group_3
# 1 2016 100 (10) 500 (50)   900 (90)
# 2 2017 200 (20) 600 (60) 1000 (100)
# 3 2018 300 (30) 700 (70) 1100 (110)
# 4 2019 400 (40) 800 (80) 1200 (120)

like image 129
anddt Avatar answered Nov 24 '25 17:11

anddt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!