Search code examples
rdataframedifferenceminmax

new column with max difference in R


I have a dataframe like:

A   1 2 3 4
B   4 5 6 9
C   2 3 4 5 

and I want to calculate the maximum difference for each row, and put it in new column:

A   1 2 3 4  3 (4-1)
B   4 5 6 9  3  (9-6)
C   1 3 4 5  4  (5-1)

Any ideas??

Thank you!!!


Solution

  • There a multiple ways in which you can this. Two are mentioned in the comments. I like to use a combination of range() and diff().

    range() gives you the minimum and maximum value in a vector. diff() gives the difference between values in a vector. Applying diff() to the output of range() will therefore give you the maximum.

    Using apply() with axis=1, does this rowwise for your data.frame:

    df$X5 <- apply(df, 1, function(x) diff(range(x)))
    df
      X1 X2 X3 X4 X5
    A  1  2  3  4  3
    B  4  5  6  9  5
    C  2  3  4  5  3