2
votes

Say we have a set of matrices of different dimensions, but with common row and column names. We would like to find the element-wise means of the matrices. xtabs() is a convenient function for this.

However, inside of for(), as.table() fails to recognize the expression calling each matrix. Creating a list of the matrices first and then calling each element of that list fails just the same.

MWE: Create matrices:

m1 <- matrix(1:9,nrow=3,ncol=3)
colnames(m1) <- c("A","B","C")
rownames(m1) <- c("A","B","C")
m2 <- matrix(10:18,nrow=3,ncol=3)
colnames(m2) <- c("A","B","C")
rownames(m2) <- c("A","B","C")
m3 <- matrix(19:22,nrow=2,ncol=2)
colnames(m3) <- c("A","B")
rownames(m3) <- c("A","B")

Use one of the matrices as a foundation to build from:

A <- m1

Join and find means:

for(i in 2:3){
  mat <- noquote(paste0("m", i))
  B   <- rbind(as.data.frame(as.table(A)), as.data.frame(as.table(mat)))
  A   <- xtabs(Freq ~ Var1 + Var2, aggregate(Freq ~ Var1 + Var2, B, mean))
}

The problem is with as.table(mat), resulting in an error:

Error in as.table.default(mat) : cannot coerce to a table

This is just a working example, the real application repeats this over thousands of matrices with different naming conventions. Inserting noquote(paste0("m", i)) directly into as.table() also fails.

Simply replacing mat with the matrix object directly works fine (i.e. as.table(m2)). Thanks!

1

1 Answers

1
votes

Here, we need get to get the value from the string identifier object

for(i in 2:3){
    mat <- get(paste0("m", i))
    B   <- rbind(as.data.frame(as.table(A)), as.data.frame(as.table(mat)))
     A   <- xtabs(Freq ~ Var1 + Var2, aggregate(Freq ~ Var1 + Var2, B, mean))
}

A
#    Var2
#Var1     A     B     C
#   A 12.25 14.75 11.50
#   B 13.25 15.75 12.50
#   C  7.50 10.50 13.50