包含原始行元素之间差异的新矩阵

时间:2012-08-21 09:44:29

标签: r matrix

我想采用现有的MxN矩阵并创建一个新的M-1xN矩阵,这样对于每一列,元素就是原始矩阵的相邻行元素之间的差异。

这个想法是数据从累积类型转变为费率类型......

例如: 我有(每列都是特定的数据系列)。

   [,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"  

我想 -

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

3 个答案:

答案 0 :(得分:4)

数字数据非常简单(不确定为什么有字符):

diff(m)

使用字符数据,这应该有效:

diff(matrix(as.numeric(m), dim(m)))

答案 1 :(得分: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)

答案 2 :(得分:0)

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

col.diff = t(diff(t(mat)))