I have a matrix called AS (in R) that collects indices of elements of an array that satisfy a certain condition. This matrix AS, however, is labeled at the top by dim1, dim2, ... which prevent me from using those indexes in typical expressions (cf. picture below). How do I get rid of these dim labels and convert this collection of indices to a regular usable matrix?
Here’s how my dim-labeled matrix looks:
And the error if I try to use the indices contained here normally:
Note: it’s not the dimensions that are incorrect here since RandPoints[1, ...] is supposed to accept 4 arguments for “...” E.g., it runs fine if I type in RandPoints[1,12,1,1,1], but I rather want that [12,1,1,1] to be supplied by calling the first row of AS as attempted in the picture.
CodePudding user response:
We could use colnames(my_matrix) <- NULL
. Here is an example:
# create a matrix
my_matrix<-matrix(1:30,ncol=3)
# assign names to your matrix
colnames(my_matrix)<-c("dim1", "dim2", "dim3")
# remove the column names
colnames(my_matrix) <- NULL
my_matrix
[,1] [,2] [,3]
[1,] 1 11 21
[2,] 2 12 22
[3,] 3 13 23
[4,] 4 14 24
[5,] 5 15 25
[6,] 6 16 26
[7,] 7 17 27
[8,] 8 18 28
[9,] 9 19 29
[10,] 10 20 30
CodePudding user response:
We may need to pass a matrix
of index for subsetting. One option is to convert the matrix
row to list
with as.list
and then cbind
so that it becomes a matrix of one row with 5 columns. The 1
is concatenated with the 4 elements of the 2nd row of 'AS' and converted to list
RandPoints[do.call(cbind, as.list(c(1, AS[2,])))]
Or another option is cbind
. Note that for matrix/data.frame
, the default option is drop = TRUE
when there is a single row/column which converts the matrix to a vector. So, change it to drop = FALSE
and cbind with 1 (to return 5 column matrix)
RandPoints[cbind(1, AS[2,, drop = FALSE])]
data
AS <- cbind(dim2 = c(3, 5), dim3 = c(1, 1), dim4 = c(1, 1), dim5 = c(1, 1))
RandPoints <- array(1:750, dim = c(5, 5, 5, 2, 3))