我有一个矩阵列表,其第一个矩阵如下所示:
$x
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
[1,] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[2,] 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0
[4,] 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0
我正在尝试创建一个相同尺寸的新矩阵,它将指示每行的第一个数字和每个连续数字之间的值差异。我想使用abs()
使此值成为此差异的绝对值。因此,在上面的例子中,预期的结果是:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
[1,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1
[3,] 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1
我知道我可以使用apply
来查看第一列和最后一列之间的区别:
abs(apply(x,1,diff, lag=15))
[1] 0 -1 0 -1
但是,我不确定如何使这个迭代过程中滞后从1增加到15以捕获整个矩阵的信息。我的原始矩阵中也有一些NA,其ID在新矩阵中返回为NA。
最终,我想使用sapply
解决方案将其应用于我的整个列表中,该列表包含500个矩阵,例如示例中的矩阵。
答案 0 :(得分:3)
我只是从每个原始矩阵的第一列构建一个单独的矩阵,然后取两个矩阵之差的abs
。我会在一分钟内用一个例子更新:
这样的事情:
> m <- matrix(sample(0:1,25,replace = TRUE),5,5)
> m
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 0 1 1
[2,] 0 0 0 1 0
[3,] 1 1 1 0 1
[4,] 1 1 1 1 0
[5,] 1 0 1 0 0
> m1 <- matrix(m[,1],5,5)
> m1
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 0 0 0
[2,] 0 0 0 0 0
[3,] 1 1 1 1 1
[4,] 1 1 1 1 1
[5,] 1 1 1 1 1
> abs(m-m1)
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 0 1 1
[2,] 0 0 0 1 0
[3,] 0 0 0 1 0
[4,] 0 0 0 0 1
[5,] 0 1 0 1 1
您可以轻松地将其转换为一个函数,以便应用于矩阵列表。
答案 1 :(得分:3)
你的意思是每行的第一个值和每个值之间的差异?
例如:
> set.seed(123)
> (m <- matrix(round(runif(64)), 4, 16))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
[1,] 0 1 1 1 0 1 1 0 1 1 0 0 0 1 0 1
[2,] 1 0 0 1 0 1 1 0 1 0 0 0 1 0 1 0
[3,] 0 1 1 0 0 1 1 1 0 0 0 0 0 1 1 0
[4,] 1 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0
> abs(m - m[, 1])
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
[1,] 0 1 1 1 0 1 1 0 1 1 0 0 0 1 0 1
[2,] 0 1 1 0 1 0 0 1 0 1 1 1 0 1 0 1
[3,] 0 1 1 0 0 1 1 1 0 0 0 0 0 1 1 0
[4,] 0 0 1 0 0 0 0 0 1 1 1 1 1 1 1 1