Search code examples
rdatatablekablekableextra

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.


Solution

  • 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)