[Rd] Use of `[` with array and resulting class

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Sat Sep 30 09:41:06 CEST 2023


Às 17:33 de 29/09/2023, Joseph Wood escreveu:
> Hello,
> 
> I recently discovered a possible inconsistency with usage of an object of
> class array.
> 
> Consider the following example:
> 
> ## Setup
> 
> a <- array(1:6, dim = c(1, 3, 2))
> a
> , , 1
> 
>       [,1] [,2] [,3]
> [1,]    1    2    3
> 
> , , 2
> 
>       [,1] [,2] [,3]
> [1,]    4    5    6
> 
> class(a)
> [1] "array"
> 
> dim(a)
> [1] 1 3 2
> 
> ## Now use `[`
> a[1,,]
>       [,1] [,2]
> [1,]    1    4
> [2,]    2    5
> [3,]    3    6
> 
> class(a[1,,])
> [1] "matrix" "array"
> 
> dim(a[1,,])
> [1] 3 2
> 
> Up until this point, it makes sense to me. Now, let's consider when dim =
> c(1, 6, 1). This is where I have a little trouble understanding the
> behavior.
> 
> ## Array with dim = c(1, any_number_here, 1)
> 
> b <- array(1:6, dim = c(1, 6, 1))
> b
> , , 1
> 
>       [,1] [,2] [,3] [,4] [,5] [,6]
> [1,]    1    2    3    4    5    6
> 
> class(b)
> [1] "array"
> 
> dim(b)
> [1] 1 6 1
> 
> ## The problem
> 
> b[1,,]
> [1] 1 2 3 4 5 6
> 
> dim(b[1,,])
> NULL
> 
> class(b[1,,])
> [1] "integer"
> 
> I would have expected:
> 
> b[1,,] ## produced the output with matrix(1:6, ncol = 1)
>       [,1]
> [1,]    1
> [2,]    2
> [3,]    3
> [4,]    4
> [5,]    5
> [6,]    6
> 
> class(b[1,,])
> [1] "matrix" "array"
> 
> dim(b[1,,])
> [1] 3 1
> 
> Is this a bug? If not, any help understanding this behaviour would be much
> appreciated.
> 
> Thanks,
> Joseph
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-devel using r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
Hello,

You are using the default behavior for objects of class "array" (and 
"matrix"), which is drop = TRUE. See ?`[`.
You probably want the second example below.


b <- array(1:6, dim = c(1, 6, 1))
# the default is drop = TRUE
b[1,,]
#> [1] 1 2 3 4 5 6

# keep the dim attribute
b[1, , , drop = FALSE]
#> , , 1
#>
#>      [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,]    1    2    3    4    5    6


Hope this helps,

Rui Barradas



-- 
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença de vírus.
www.avg.com



More information about the R-devel mailing list