R根据条件填充矩阵

时间:2018-04-19 11:57:58

标签: r matrix conditional-statements fill

有一个矩阵5x5,其中行和和列总和给出

mat1<-matrix(0,ncol = 5, nrow = 5)
colnames(mat1) <- c("A","B","C","D","E")
rownames(mat1) <- c(1:5)
mat1<-rbind(mat1, Sum = 2)
mat1<-cbind(mat1, Sum = c(1,3,2,3,1,""))
View(mat1)

行和列的总和意味着,不能超过总和的单元格可以填充1。 必须填充矩阵,以尽可能满足条件(每个矩阵元素的行和和列总和)。
但是每行的单元格必须在定义区间内填充:

mat2[1,]<-c(1,1,0,0,0)
mat2[2,]<-c(1,1,1,1,0)
mat2[3,]<-c(0,1,1,0,0)
mat2[4,]<-c(0,1,1,1,1)
mat2[5,]<-c(0,0,0,1,1)
mat2<-rbind(mat2, Sum = 2)
mat2<-cbind(mat2, Sum = c(1,3,2,3,1,"")) 
View(mat2)

因此,我希望收到以下矩阵:

enter image description here

否则,矩阵只能在间隔内填充,在下面的矩阵中是红色的:

enter image description here

提前谢谢你!

1 个答案:

答案 0 :(得分:2)

您的问题有多种解决方案。查看使用Patefield's algorithm的代码(每次运行时,您都有不同的解决方案,这里我给出3个不同的示例):

mat1 <- r2dtable(n=1, r=c(1,3,2,3,1), c=rep(2,5))[[1]]

colnames(mat1) <- c("A","B","C","D","E")
rownames(mat1) <- c(1:5)
mat1 <- rbind(mat1, Sum = 2)
mat1 <- cbind(mat1, Sum = c(1,3,2,3,1,""))

mat1
     A   B   C   D   E   Sum
1   "0" "1" "0" "0" "0" "1"
2   "1" "0" "0" "1" "1" "3"
3   "0" "0" "1" "1" "0" "2"
4   "0" "1" "1" "0" "1" "3"
5   "1" "0" "0" "0" "0" "1"
Sum "2" "2" "2" "2" "2" ""
     A   B   C   D   E   Sum
1   "0" "0" "0" "0" "1" "1"
2   "2" "0" "1" "0" "0" "3"
3   "0" "0" "1" "1" "0" "2"
4   "0" "1" "0" "1" "1" "3"
5   "0" "1" "0" "0" "0" "1"
Sum "2" "2" "2" "2" "2" ""
     A   B   C   D   E   Sum
1   "0" "0" "0" "1" "0" "1"
2   "0" "1" "1" "0" "1" "3"
3   "0" "1" "0" "0" "1" "2"
4   "1" "0" "1" "1" "0" "3"
5   "1" "0" "0" "0" "0" "1"
Sum "2" "2" "2" "2" "2" ""