[R] merging tables based on both row and column names

Giorgio Garziano giorgio.garziano at ericsson.com
Tue Sep 29 13:22:14 CEST 2015


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')

> test1
    x1  x2
y1 0.1 0.2
y2 0.3 0.3
y3 0.1 0.1

> test2
    x1  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
     }
  }
}


> m
x1        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]]



More information about the R-help mailing list