0

The problem:
Using R, I have two arrays, both with the same type of data (e.g. same row, column, and/or layer names). However, they have different dimensions. The row & column names are partially overlapping. That is, most levels of row and column factors appear in both arrays, but some are unique to each array. I want to take one of these arrays, and pare it down so that is consists ONLY of the row & column levels that are common to both arrays. I have been able to accomplish this before by writing my own very convoluted function, but it seems like this really ought to be a simple operation. Can anybody point me in the right direction for this?

Here is some example code of what I thought was an unnecessarily laborious way to accomplish this. In this case, sp.ixn.core was a smaller 2D array, and I wanted to pare down a 3D array so the rows and columns matched sp.ixn.core ... the last bit was me double checking to see if the numbers added up correctly.

temp=table(data$plant,data$Species,data$jdate)
temp2=array(,dim=c(nrow(sp.ixn.core),ncol(temp),dim(temp)[3]))

for (i in 1:length(rownames(sp.ixn.core))){
temp2[i,,] = temp[rownames(temp) == rownames(sp.ixn.core)[i],,]
}

colnames(temp2) = colnames(temp)
temp3=array(,dim=c(nrow(sp.ixn.core),ncol(sp.ixn.core),dim(temp)[3]))
for (i in 1:length(colnames(sp.ixn.core))){
temp3[,i,] = temp2[,colnames(temp2) == colnames(sp.ixn.core)[i],]
}
dim(temp3)

sp.ixn.core.tbl = temp3
dimnames(sp.ixn.core.tbl)[[3]] = dimnames(temp)[[3]]
dimnames(sp.ixn.core.tbl)[[2]] = colnames(sp.ixn.core)
dimnames(sp.ixn.core.tbl)[[1]] = rownames(sp.ixn.core)
dimnames(sp.ixn.core.tbl)

for (i in 1:nrow(sp.ixn.core)){
    if (sum(sp.ixn.core.tbl[i,,]) == rowSums(sp.ixn.core)[i])
        print("yes")
}

for (i in 1:ncol(sp.ixn.core)){
    if (sum(sp.ixn.core.tbl[,i,]) == colSums(sp.ixn.core)[i])
        print("yes")
}
digEmAll
  • 56,430
  • 9
  • 115
  • 140

1 Answers1

0

I think you might just need:

newtemp <- temp[ rownames(temp) %in% rownames(sp.ixn.core),
                 colnames(temp) %in% colnames(sp.ixn.core),
                 dimnames(temp)[3] %in% dimnames(sp.ixn.core)[3] ]

And you could have just used 'dimnames' since dimnames(x)[1] == rownames(x). As nograpes suggested would be better to test this against your actual data objects. I'm a little worried here that your table call may return an object with NULL dimnames.

IRTFM
  • 258,963
  • 21
  • 364
  • 487