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

Categories

0 votes
919 views
in Technique[技术] by (71.8m points)

dplyr - bind two dataframe in r and fusionnate two columns

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...