0

I want to take an existing MxN matrix and create a new M-1xN matrix such that for each columns, the elements are the difference between adjacent row elements of the original matrix.

The idea is the data goes from a cumulative type to a rate type...

eg: I have (where each column is a specific data series).

   [,1]  [,2] [,3] 
[1,] "17"  "16" "15" 
[2,] "34"  "32" "32" 
[3,] "53"  "47" "48"  
[4,] "72"  "62" "63" 
[5,] "90"  "78" "79"  
[6,] "109" "94" "96"  

I would like -

   [,1]  [,2] [,3] 
[1,] "17"  "16" "17"  
[2,] "19"  "15" "16" 
[3,] "19"  "15" "15" 
[4,] "18"  "16" "16" 
[5,] "19"  "16" "17" 
Kara
  • 6,115
  • 16
  • 50
  • 57
Syscrusher
  • 3
  • 1
  • 3

3 Answers3

4

It's very simple for numerical data (not sure why you have characters):

diff(m)

With the character data, this should work:

diff(matrix(as.numeric(m), dim(m)))
Lubo Antonov
  • 2,301
  • 14
  • 18
1

It's a bit strange with the character format, but here's a way:

# Set up the data
mymat<-matrix(c("17","16","15",
  "34","32","32",
  "53","47","48" ,
  "72","62","63",
  "90","78","79" ,
  "109","94","96"),nrow=6,byrow=TRUE)

Use the apply function with an anonymous function centered around diff.

apply(mymat, 2, function(x)as.character(diff(as.numeric(x))))

#      [,1] [,2] [,3]
# [1,] "17" "16" "17"
# [2,] "19" "15" "16"
# [3,] "19" "15" "15"
# [4,] "18" "16" "16"
# [5,] "19" "16" "17"

If the data are numeric to begin with and a numeric result is desired, then the above could be simplified to

apply(mymat, 2, diff)
BenBarnes
  • 19,114
  • 6
  • 56
  • 74
1

In case you want to subtract the columns of a matrix (and not the rows), try:

col.diff = t(diff(t(mat)))
Alex Witsil
  • 855
  • 8
  • 22