Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hello I have 2 dataframe such as

df1

COL1 total 
A    23
B    76
C    89
D    29
E    9
F    2

df2

COL1 total 
A    2
B    9
C    1
D    21
E    5
F    1

And I would like to bind the two dataframe and fusionnate the two total columns such as :

df3

COL1 total 
A    23(2)
B    76(9)
C    89(1)
D    29(21)
E    9(5)
F    2(1)
question from:https://stackoverflow.com/questions/65830093/bind-two-dataframe-in-r-and-fusionnate-two-columns

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this. You can bind data by rows and summarise using toString() in order to arrange values. Finally, you can clean the data to get the expected order using mutate(), gsub() and paste0():

library(dplyr)
#Code
new <- df1 %>% bind_rows(df2) %>%
  group_by(COL1) %>%
  summarise(total=toString(total)) %>%
  mutate(total=gsub(', ','(',total),
         total=paste0(total,')'))

Output:

# A tibble: 6 x 2
  COL1  total 
  <chr> <chr> 
1 A     23(2) 
2 B     76(9) 
3 C     89(1) 
4 D     29(21)
5 E     9(5)  
6 F     2(1)  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...