如何在矩阵

时间:2016-08-27 02:51:55

标签: r matrix random

我是R的新手并且学习R的介绍。我有一个大矩阵(100000的倍数)和几百列。我在下面给出一个示例矩阵。

set.seed(1)
m4 <- matrix(sample(0:3,5*4, replace=TRUE),5,4) # sample event matrix
m4GROUP <- data.frame( X1=rowSums(m4[,1, drop=FALSE]), X2=rowSums(m4[,2:3]), 
                       X3=rowSums(m4[,4, drop=FALSE]) ) # 1 column
m4GroupColID <- colSums(m4GROUP) # coln sum to generate a matrix per col

输出

m4
     [,1] [,2] [,3] [,4]
[1,]    1    3    0    1
[2,]    1    3    0    2
[3,]    2    2    2    3
[4,]    3    2    1    1
[5,]    0    0    3    3

> m4GROUP # group by Col 1, Cols 2-3, Col4
  X1 X2 X3
1  1  3  1
2  1  3  2
3  2  4  3
4  3  3  1
5  0  3  3

> m4GroupColID
X1 X2 X3 
 7 16 10 
  • 我需要为每行生成一个5 x 4 x总eventsID的矩阵 组。在这种情况下,我需要获得4个矩阵4个cols 每列5 x max(M4Group)的尺寸。
  • 对于每一行,ID都被替换(即,如果我们,则可以重复相同的ID 在列之间形成两列或更多列的分组 小组)
  • 在Row之间,ID不会被替换(即前一行的ID可以 不能分配给具有两个或的同一组中的下一行 更多专栏);但是,可以在组中的列之间分配当前行的ID。
  • 最后,对于由多个列组成的组,每个的totalIDs 行可以随机分配。这确保了团队拥有更多 一列受到ID的影响。

对不起,这是一个很长的帖子,我只是不知道如何缩短这一点而不会失去本质。

col 1的总事件ID为7,cols 2-3为16,col.4为10:

最终输出,例如在每列的cols 2-3中随机分配如下:cols的ID是:1-7,8-23,24-33。

Col 1    Col 2        Col 3        col 4
1 0 0    8 9 10 0     0 0 0 0      24 0 0 
2 0 0    11 12 13 0   0 0 0 0      25 26 0
3 4 0    14 15 17 0   14 16 0 0    27 28 29
5 6 7    18 20 0 0    18 0 0 0     30 0 0 
0 0 0    0 0 0 0      21 22 23 0   31 32 33

如果我们每行只有一个事件,则id生成和分发相当简单。

m1 <- matrix(sample(0:1,5*4, replace=TRUE),5,4) # sample event matrix
ifelse(m1==0, 0, matrix(sample(1:1,5*4, replace = T), 5,4)) # works for one  ID assignment

我开始使用循环,知识,因为循环在R中不是更快。但是,无论是否有替换,我都会遇到错误。我肯定需要(在同一行上的Replacement = True)和行之间的(Replacement = False)。

nc <- max(m4GROUP$X1)
i <- 1
j <- 1
while(i <- 5){
  if(m4[i,j] == 0){
    m[i,j] <- matrix(0, 5, nc)
  } else {
    if(m4[i,j] == 1){
      m[i,j] <- matrix(sample(1, i*nc, replace=T), 5, nc)
    } else {
      m[i,j] <- matrix(sample(2, i*nc, replace=T), 5, nc)
    }
  }
}

我知道这不对。我收到以下错误。

Error in m[i, j] <- matrix(sample(0, i * nc, replace = T), 5, nc) : 
  number of items to replace is not a multiple of replacement length
Error in m[i, j] <- matrix(0, 5, nc) : 
  number of items to replace is not a multiple of replacement length

我还尝试了以下方法:我没有得到满足上述要点的结果;此外,它们以每行的相同ID开头。我只得到3行而不是4行。最后,考虑到我的实际样本量,这并不理想。

size <- c(1:7, 1:16, 1:9, 10)
startID <- which(size==1)
endIDs <- c(which(size==1)[-1] -1, length(size))
mats <- mapply(function(x, y) t(size[seq(x, y)]), startID, endIDs)
library(plyr)
m <- (rbind.fill.matrix(mats))

输出:

m
     1 2 3 4 5 6 7  8  9 10 11 12 13 14 15 16
[1,] 1 2 3 4 5 6 7 NA NA NA NA NA NA NA NA NA
[2,] 1 2 3 4 5 6 7  8  9 10 11 12 13 14 15 16
[3,] 1 2 3 4 5 6 7  8  9 10 NA NA NA NA NA NA

我再次为这篇长篇文章感到遗憾,但感谢您不仅要阅读本文,还要感谢帮助。

0 个答案:

没有答案
相关问题