Do not take measurements when connecting a 3-dimensional array

Let A be a 1 x 2 x 2 -array:

 > A <- array(0, dim=c(1,2,2)) > A , , 1 [,1] [,2] [1,] 0 0 , , 2 [,1] [,2] [1,] 0 0 

Then A[,,1] dimensionless:

 > A[,,1] [1] 0 0 

I would like to:

  [,1] [,2] [1,] 0 0 

The drop argument does not give what I want:

 > A[,,1,drop=FALSE] , , 1 [,1] [,2] [1,] 0 0 

I find it annoying. And buggies, because R identifies vectors for column matrices, not rows.

Of course, I could do matrix(A[,,1], 1, 2) . Is there a more convenient way?

+5
source share
4 answers

We can just assign dim based on MARGIN , which we extract

 `dim<-`(A[, ,1], apply(A, 3, dim)[,1]) # [,1] [,2] #[1,] 0 0 

Using another example

 B <- array(0, dim = c(2, 1, 2)) `dim<-`(B[, ,1], apply(B, 3, dim)[,1]) # [,1] #[1,] 0 #[2,] 0 

If we use a batch solution, then adrop from abind can get the expected output

 library(abind) adrop(A[,,1,drop=FALSE], drop = 3) # [,1] [,2] # [1,] 0 0 adrop(B[,,1,drop=FALSE], drop = 3) # [,1] #[1,] 0 #[2,] 0 
+2
source
 t(A[,,1]) [,1] [,2] [1,] 0 0 

I, though from your comment, that R identifies the vector for the column matrix. I think transposing gives what you want and is a bit more convenient.

+1
source

Unfortunately, this is not so simple. With drop = TRUE any size 1 discarded. You can see this if you look at the source of ArraySubset from src / main / subset.c . At the end of the function, we see the following:

 if (drop) DropDims(result); 

The DropDims function DropDims defined in src / main / array.c . In this function, we see that

 n = 0; for (i = 0; i < ndims; i++) if (dim[i] != 1) n++; 

and in another place of the function we see that the size sizes that one of them is ignored.

It is annoying that R determines the behavior of the droplet from the result. It would be more natural if R only dropped indexed length sizes of one, so that the behavior would be what you expected in this example.

All that was said the following is ugly, the error may work in your use case:

 `dim<-`(A[,,1], dim(A)[-3]) #> [,1] [,2] #> [1,] 0 0 

This doesn't generalize very well, but works if you index on one coordinate.

+1
source

Another batch solution: keep package.

 > library(keep) > A <- karray(0, dim=c(1,2,2)) > A[,,1] [,1] [,2] [1,] 0 0 attr(,"class") [1] "keep" "numeric" 
0
source

Source: https://habr.com/ru/post/1273857/


All Articles