行名称和列名称的不同大小的平均矩阵

时间:2014-07-24 15:11:05

标签: r matrix size

如何平均不同大小的不同矩阵(可能超过2个)? Rownames和colnames可用于匹配:

x1<- as.data.frame((matrix(c(0,0,1,0,2,3,1,1,1),nrow=3)))
colnames(x1)<-c('1','3','4')
rownames(x1)<- c('1','2','4')
> x1
  1 3 4
1 0 0 1
2 0 2 1
4 1 3 1


x2<- as.data.frame((matrix(c(1,1,2,2,0,0,0,2,1,1,0,1,1,0,1,1),nrow=4)))
colnames(x2)<-c('1','2','3','4')
rownames(x2)<- c('1','2','3','4')
>x2
  1 2 3 4
1 1 0 1 1
2 1 0 1 0
3 2 0 0 1
4 2 2 1 1

x3<- matrix(c(0.5,0,0.5,1  ,0.5,0,1,0.5,  2,0,0,1,   1.5,2,1.5,1),nrow=4, byrow = T)
colnames(x3)<-c('1','2','3','4')
rownames(x3)<- c('1','2','3','4')

结果如下:     x3&lt; - averageMatDiffSizes(x1,x2)

x3
    1 2   3   4
1 0.5 0 0.5 1.0
2 0.5 0 1.0 0.5
3 2.0 0 0.0 1.0
4 1.5 2 1.5 1.0

1 个答案:

答案 0 :(得分:2)

你可以这样做:

xNew <- matrix(ncol=ncol(x2), nrow=nrow(x2), dimnames=list(1:4,1:4)) #as x2 is the larger dimension in the example.
# If both have different sizes and some columns are missing in both
# Create using ?union(). e.g. ncol=length(union(colnames(x1),colnames(x2))), similarly
# for nrow.

indx <- outer(rownames(x1),colnames(x1), paste)
indx1 <- outer(rownames(x2),colnames(x2), paste)
xNew[match(indx,indx1)] <- unlist(x1)
lst <- list(xNew, x2)
x3 <- do.call(`+`, lst)/length(lst)
x3[is.na(x3)] <- unlist(x2)[!indx1%in% indx]

  x3
#    1 2   3   4
# 1 0.5 0 0.5 1.0
# 2 0.5 0 1.5 0.5
# 3 2.0 0 0.0 1.0
# 4 1.5 2 2.0 1.0