如何使用R查找矩阵中发生更改的次数

时间:2018-06-12 19:27:06

标签: r matrix

假设我有一个矩阵

 >tmp
       [,1] [,2] [,3]
  [1,]    0    0    3
  [2,]    0    2    0
  [3,]    1    0    0
  [4,]    1    0    0
  [5,]    0    2    0
  [6,]    1    0    0
  [7,]    0    0    3
  [8,]    0    0    3
  [9,]    0    2    0

我现在想要计算矩阵中的变化次数,所以让我们说在第一行中我有一个3,然后它在下一行中变为2,依此类推。我想将这些更改添加到这样的表中:

      1    2    3
  1   1    1    1
  2   2    0    0
  3   0    2    1

所以它说1改为1,1次。 1改为2,1时。 2改为1,2次等。我已经尝试了一段时间,但我无法弄清楚一个聪明的方法。我在考虑在R中使用函数table(),但我不知道如何。有没有人有这个问题的智能解决方案?

谢谢!

2 个答案:

答案 0 :(得分:3)

t2 = as.vector(t(tmp))
t2 = t2[t2 != 0]
trans = data.frame(from = t2[-length(t2)], to = t2[-1])
with(trans, table(from, to))
#     to
# from 1 2 3
#    1 1 1 1
#    2 2 0 0
#    3 0 2 1

当然,您可以完全跳过数据框并跳转到table(from = t2[-length(t2)], to = t2[-1])

使用此数据:

tmp = as.matrix(read.table(text = "      0    0    3
      0    2    0
      1    0    0
      1    0    0
      0    2    0
      1    0    0
      0    0    3
      0    0    3
      0    2    0"))

答案 1 :(得分:1)

library(zoo)
library(magrittr)

tmp %>% 
  apply(1, function(x) x[x!=0]) %>% # Get non-zero element from each row
  rollapplyr(2, I) %>% # Make matrix whose rows are all 2-windows of above
  {table(from = .[,1], to = .[,2])} # make into table
#     to
# from 1 2 3
#    1 1 1 1
#    2 2 0 0
#    3 0 2 1

使用的数据

tmp <- data.table::fread("
   a      b   c     d
  [1,]    0    0    3
  [2,]    0    2    0
  [3,]    1    0    0
  [4,]    1    0    0
  [5,]    0    2    0
  [6,]    1    0    0
  [7,]    0    0    3
  [8,]    0    0    3
  [9,]    0    2    0
")[, -'a']
tmp <- as.matrix(tmp)