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
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)))
In case you want to subtract the columns of a matrix (and not the rows), try:
col.diff = t(diff(t(mat)))
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)