Search code examples
rmatrixrowdifference

R how to calculate difference between two matrix rows?


This seems like a rudimentary question, but i can't find a solution that would work for me. I have a matrix results.m

> head(results.m)
Perplexity Topics
[1,] 550.8307 2
[2,] 479.3954 3
[3,] 424.5563 4
[4,] 359.7448 5
[5,] 339.7989 6
[6,] 314.3516 7

I don't understand how can i create a column diff that will be equal to the difference between two rows (e.g. for row 2 the value would be -71.4353, and empty in row 1) and a column chg that will be equal to percent change between two rows (13 for row 2).

> data.frame(diff(as.matrix(results.m))) game me an error

Error in r[i1, , drop = FALSE] - r[-nrow(r):-(nrow(r) - lag + 1L), , drop = FALSE] :   non-numeric argument to binary operator

> tail(results.m, -1) - head(results.m, -1) also gave an error

 Error in tail(results.m, -1) - head(results.m, -1) :    non-numeric
 argument to binary operator

What am doing wrong here?


Solution

  • you can add a column by cbind it to the existing matrix. so you just have to cbind the difference between the two other columns

    results.m = cbind(results.m, c(0,diff(results.m[,1])))
    

    afterwards you can give that column an appropriate name if you want to do so.

    colnames(results.m)[3] <- "diff"