I currently have an array which is:
我目前有一个数组是:
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)
new.array <- array(c(vector1,vector2),dim = c(3,3,100))
print(new.array)
, , 1
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
, , 2
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
...
I am wondering how I can subtract just the second from the third row in each matrix, while preserving the array structure. For example I would like to obtain:
我想知道如何从每个矩阵的第三行中减去第二行,同时保留数组结构。例如,我想获得:
, , 1
[,1] [,2] [,3]
[1,] -6 1 1
, , 2
[,1] [,2] [,3]
[1,] -6 1 1
...
Thanks.
2 个解决方案
#1
8
This will do it:
这样做:
new.array[3, , , drop = FALSE] - new.array[2, , , drop = FALSE]
The drop = FALSE
is to make sure that the subset of array has the same dimmensions as the original array.
drop = FALSE是为了确保数组的子集具有与原始数组相同的dimmensions。
#2
5
You can do this:
你可以这样做:
If you run a dim(new.array)
it will return three dimesions in order of row, column and last dimension which represents your number of matrices .To access any particular matrix in order. You have to do : array[,,1] will fetch first matrix of that particular array and so on. In this case the total number of matrices formed is 100. Run a dim(new.array)
and see for yourself. Using lapply
on these 100 small matrices. you can subtract the third row from second row. like below.
如果运行dim(new.array),它将按行,列和最后一维的顺序返回三个维数,表示矩阵的数量。按顺序访问任何特定的矩阵。你必须这样做:array [,, 1]将获取该特定数组的第一个矩阵,依此类推。在这种情况下,形成的矩阵总数为100.运行一个暗淡(new.array)并亲眼看看。在这100个小矩阵上使用lapply。你可以从第二行中减去第三行。如下。
> lapply(1:100, function(x)new.array[,,x][2,] - new.array[,,x][3,])
#1
8
This will do it:
这样做:
new.array[3, , , drop = FALSE] - new.array[2, , , drop = FALSE]
The drop = FALSE
is to make sure that the subset of array has the same dimmensions as the original array.
drop = FALSE是为了确保数组的子集具有与原始数组相同的dimmensions。
#2
5
You can do this:
你可以这样做:
If you run a dim(new.array)
it will return three dimesions in order of row, column and last dimension which represents your number of matrices .To access any particular matrix in order. You have to do : array[,,1] will fetch first matrix of that particular array and so on. In this case the total number of matrices formed is 100. Run a dim(new.array)
and see for yourself. Using lapply
on these 100 small matrices. you can subtract the third row from second row. like below.
如果运行dim(new.array),它将按行,列和最后一维的顺序返回三个维数,表示矩阵的数量。按顺序访问任何特定的矩阵。你必须这样做:array [,, 1]将获取该特定数组的第一个矩阵,依此类推。在这种情况下,形成的矩阵总数为100.运行一个暗淡(new.array)并亲眼看看。在这100个小矩阵上使用lapply。你可以从第二行中减去第三行。如下。
> lapply(1:100, function(x)new.array[,,x][2,] - new.array[,,x][3,])