rdataframesumamplitudeabsolute-value

Add a row to a dataframe showing amplitude (max of the sum of the positive or the negative values)


I'd like to insert a last row to a dataframe that would show either the sum of the positive values or the sum of the negative value per column, whichever sum has the greatest amplitude.

The final table would look like this with the last row ("MaxAmplitude") being the result I would like to obtain:

  c("A", "B", "C", "Max Amplitude")  X1  X2  X3  X4  X5
1                                 A -30  10  10  -2   8
2                                 B   5  50 100 -10 -10
3                                 C -10 -30   1  -1   3
4                     Max Amplitude -40  60 111 -13  11

My idea was a multiple step approach, where I would successively add several rows:

My issue is that I'd like to do it without having to add that many rows to the dataframe. Besides, I don't know how I could do to diplay the negative sign in case the sum of negative values has the greatest amplitude (I would lose this information if I compare absolute value).

Would someone have any solution as to how I could code this please? Thanks a lot for your help!

df <- cbind(c("A","B","C"),data.frame(matrix(c(-30,5,-10,
                                                       10,50,-40,
                                                       10,100,1,
                                                       -2,-10,-1,
                                                       8,-10,3
                                                       ), nrow = 3, ncol = 5)))

Solution

  • Is this what you want ? Also , apply return a matrix not data.frame

    apply(df[,2:6],2,function(x) sum(x[which((x>0)==(sum(x)>0))]))
    
    
     X1  X2  X3  X4  X5 
    -40  60 111 -13  11 
    

    Just df[nrow(df)+1,]=c('Max Amplitude',c(apply(df[,2:6],2,function(x) sum(x[which((x>0)==(sum(x)>0))]))))

    > df
      c("A", "B", "C")  X1  X2  X3  X4  X5
    1                A -30  10  10  -2   8
    2                B   5  50 100 -10 -10
    3                C -10 -40   1  -1   3
    4    Max Amplitude -40  60 111 -13  11