Giorgio Garziano
2015-Oct-01 15:26 UTC
[R] merging tables based on both row and column names
I reworked Frank Schwidom's solution to make it shorter than its original version. test1 <- (rbind(c(0.1,0.2),0.3,0.1)) rownames(test1)=c('y1','y2','y3') colnames(test1) = c('x1','x2'); test2 <- (rbind(c(0.8,0.9,0.5),c(0.5,0.1,0.6))) rownames(test2) = c('y2','y5') colnames(test2) = c('x1','x3','x2') lTest12 <- list(test1, test2) namesRow <- unique( unlist( lapply(lTest12, rownames))) namesCol <- unique( unlist( lapply(lTest12, colnames))) # here reworked code starts tmp1 <- sapply(lTest12, function(x) as.vector( x[match(namesRow, rownames(x)), match(namesCol, colnames(x))])) tmp2 <- apply(tmp1, 1, function(x) { na.omit(x) }) dimnames1 <- list(namesRow, namesCol) tmp3 <- array(data = tmp2, dim = sapply(dimnames1, length), dimnames = dimnames1) tmp3 > paste(tmp3) [1] "0.1" "c(0.3, 0.8)" "0.1" "0.5" "0.2" [6] "c(0.3, 0.5)" "0.1" "0.6" "numeric(0)" "0.9" [11] "numeric(0)" "0.1" > tmp3 x1 x2 x3 y1 0.1 0.2 Numeric,0 y2 Numeric,2 Numeric,2 0.9 y3 0.1 0.1 Numeric,0 y5 0.5 0.6 0.1 > > tmp3["y2","x1"] [[1]] [1] 0.3 0.8 > tmp3["y2","x2"] [[1]] [1] 0.3 0.5 [[alternative HTML version deleted]]