apply statement is not working as expected

Table.arr consists of a 2x2 matrix of counts followed by a third column of target rates. I would have done the code this way:

Error2.f <- function(mat){
1 - sum(diag(mat[,1:2]))/sum(mat[,1:2]) }
apply(Table.arr,c(1,2),Error2.f) or 
sd.mat <- apply(Error.arr,2:3,sd)
Mean.mat <- apply(Error.arr,2:3,mean)

I get error - Error in mat[, 1:2] : incorrect number of dimensions

sd.mat <- apply(Error.arr,2:3,sd)
Mean.mat <- apply(Error.arr,2:3,mean)

Table.arr is randomForest output . It is a list of 2x3 matrices

, , 1, 1, 1, 1

 [,1] [,2]      [,3]

[1,] 152 30 0.1648352
[2,] 55 73 0.4296875


I thought the two commas referred to the rows and columns of the output matrices.
Can you help please? Thank you.


your apply says to take each cell in turn MARGINS=c(1,2) and apply a function that expects a matrix input ; but its not a matrix input, its a scalar value, the value of a cell of Table.arr

do you mean to directly apply Error2.f on the 2x2 subset to the top left of Table.arr ?
that would be


I have just learned about the concept of dimension when working with the apply function. I came up with the following:

Error.arr <- apply(Table.arr,c(3:6),Error2.f)

3:6 refer to dimensions 3,4,5,6. This will change with different analyses.

Your answer is a still another way of looking at the apply statement.
I am getting confused. Can you suggest a source of information about apply?
Youtube videos and white papers are always good.

Thank you for replying.

Does this work for you or does it give you an error that MARGIN does not match dim(X) ?

Re: Error.arr <- apply(Table.arr,c(3:6),Error2.f)
This is working.
There is a lot of processing going on and I am studying the dimension issue as I work out the random forest cross validation code. To answer your question and improve on mine will take more effort on my part. I am doing multiple runs of my function and comparing the output. When I have more output I will summarize and may contact RStudio again about this.

I am thinking about your original reply.
Is there a difference in 1:2 and c(1:2) in the apply statement?
Is there a difference in 1,2 and c(1,2) in the apply statement?
Thank you. MM

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.