Search code examples
rconditional-statementsgroup

Group rows based on matching condition from another dataframe


I have a CSV file that look like this:

I want to group all the values in the name column under the chain column.

So, my final table would look like this:

     Acala           Algorand         Algorand-borrowed
1    Acala Dollar    Algodex          Algofi Lend
2    Acala LCDOT     Algofi Lend      Folks Finance

I tried to look up how to use group or merge function for this, but I wasn't successful. Is there an efficient way to do this?


Solution

  • Solution using data.table

    library(data.table)
    
    setDT(dt)
    
    dcast(dt, rowid(chain) ~ chain, value.var = "name")[, -1]
    

    Output

              Acala    Algorand Algorand-borrowed
    1: Acala Dollar     Algodex       Algofi Lend
    2:  Acala LCDOT Algofi Lend     Folks Finance
    3:   Acala Swap        <NA>              <NA>
    

    Sample data

    dt <- data.frame(
      chain = c(rep(c("Acala", "Algorand", "Algorand-borrowed"), 2), "Acala"),
      name = c("Acala Dollar", "Algodex", "Algofi Lend", "Acala LCDOT", "Algofi Lend", "Folks Finance", "Acala Swap")
    )