Search code examples
rdataframerow

Add extra row to dataframe based on values of other rows


I have a dataframe with two rows of data. I would like to add a third row with values representing the difference between the previous two.

The data is in the following format:

Month   A   B   C   D   E   F
Jan     1   2   4   8   4   1
Feb     1   1   4   5   2   0

I would like to add an extra row with a calculation to give the change across the two months:

Month   A   B   C   D   E   F
Jan     1   2   4   8   4   1
Feb     1   1   4   5   2   0
Change  0   1   0   3   2   1

I've been looking at various functions to add additional rows including rbind and mutate but I'm struggling to perform the calculation in the newly created row.


Solution

  • As it's just two rows you can subtract the individual rows and rbind the difference

    rbind(df, data.frame(Month = "Change", df[1, -1] - df[2, -1]))
    
    #   Month A B C D E F
    #1    Jan 1 2 4 8 4 1
    #2    Feb 1 1 4 5 2 0
    #3 Change 0 1 0 3 2 1