Giorgio Garziano
2015-Sep-29 11:22 UTC
[R] merging tables based on both row and column names
Another approach: test1 <- data.frame(rbind(c(0.1,0.2),0.3,0.1)) rownames(test1) = c('y1','y2','y3') colnames(test1) = c('x1','x2'); test2 <- data.frame(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')> test1x1 x2 y1 0.1 0.2 y2 0.3 0.3 y3 0.1 0.1> test2x1 x3 x2 y2 0.8 0.9 0.5 y5 0.5 0.1 0.6 t1.r <- rownames(test1) t2.r <- rownames(test2) t1.c <- colnames(test1) t2.c <- colnames(test2) col <- unique(union(t1.c, t2.c)) ncol <- length(col) row <- unique(union(t1.r, t2.r)) nrow <- length(row) m <- matrix(list(), nrow=nrow, ncol=ncol) rownames(m) <- row colnames(m) <- col for (i in 1:nrow) { for (j in 1:ncol) { rowname <- row[i] colname <- col[j] v <- c() if (!is.null(test1[rowname, colname]) && !is.na(test1[rowname, colname])) { v <- c(test1[rowname, colname]) } if (!is.null(test2[rowname, colname]) && !is.na(test2[rowname, colname])) { v <- c(v, test2[rowname, colname]) } if (!is.null(v)) { m[rowname, colname] <- list(v) } else { m[rowname, colname] <- NA } } }> mx1 x2 x3 y1 0.1 0.2 NA y2 Numeric,2 Numeric,2 0.9 y3 0.1 0.1 NA y5 0.5 0.6 0.1> m["y2",]$x1 [1] 0.3 0.8 $x2 [1] 0.3 0.5 $x3 [1] 0.9 -- Giorgio Garziano [[alternative HTML version deleted]]
Thank you, *Frank* and *Giorgio* for your replies. Both of your solutions work for my need. *Frank*, I ended up using your codes. Like that it's short. For multiple test data frame, I ended up creating a list in the beginning and put each test data frame into the list as such: ltest = list(); ltest[[i]]=test; Thanks again for your help. Lin -- View this message in context: http://r.789695.n4.nabble.com/merging-tables-based-on-both-row-and-column-names-tp4712905p4712995.html Sent from the R help mailing list archive at Nabble.com.