Ahir Bhairav Orai
Ahir Bhairav Orai

Reputation: 697

r combine results from two tables into one

My first table is like this.

               Dante      Inferno      Purgatorio    Paradiso
       A       1477       445           NA           191
       B       1427       751           359          360
       C       NA         273          3095          NA
       D       1614       NA            43           116

This is my second table

               Dante      Inferno      Purgatorio    Paradiso
       A       658        445           NA           116
       B       653        751           97           360
       C       NA         273           2095          NA
       D       703        NA            43           103

What I am trying to accomplish is a table like this

               Dante       Inferno      Purgatorio    Paradiso
       A       1477(658)   445(445)     NA            191(116)
       B       1427(653)   751(751)     359(97)       360(360)
       C       NA          273(273)     3095(2095)    NA
       D       1614(703)   NA           43(43)        116(103)

Values from the second table are within brackets for the matching column and row (same cell).

Any suggestions on how to create this table is much appriciated. Thanks in advance.

Upvotes: 0

Views: 112

Answers (2)

hi_everyone
hi_everyone

Reputation: 333

I'd do something like this, and worry about the NA afterwards...

A <- as.data.frame(matrix(1:16,4))  
B <- as.data.frame(matrix(17:32,4))

my_paste <- \(a,b) paste0(a," (",b,")")  
C <- mapply(my_paste,A,B)

Then you'd might do something like

C[C == my_paste(NA,NA)] <- NA

to clean up the NAs

Upvotes: 1

Onyambu
Onyambu

Reputation: 79208

df3 <- df1
df3[] <- sub('NA.+', 'NA', mapply(sprintf, '%s(%s)', df1, df2))

df3
      Dante  Inferno Purgatorio Paradiso
A 1477(658) 445(445)         NA 191(116)
B 1427(653) 751(751)    359(97) 360(360)
C        NA 273(273) 3095(2095)       NA
D 1614(703)       NA     43(43) 116(103)

Upvotes: 1

Related Questions