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" 
4

3 回答 3

4

数字数据非常简单(不知道为什么你有字符):

diff(m)

使用字符数据,这应该可以工作:

diff(matrix(as.numeric(m), dim(m)))
于 2012-08-21T10:04:12.633 回答
1

字符格式有点奇怪,但这里有一种方法:

# 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)

将该apply函数与以 . 为中心的匿名函数一起使用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"

如果数据以数字开头并且需要数字结果,则上述可以简化为

apply(mymat, 2, diff)
于 2012-08-21T09:58:05.200 回答
0

如果您想减去矩阵的列(而不是行),请尝试:

col.diff = t(diff(t(mat)))
于 2016-07-20T17:10:56.993 回答