使用整数值矩阵来确定字符串矩阵中的字符串长度

时间:2016-12-02 07:06:49

标签: r matrix operations

我正在尝试创建一个不同长度的字符串矩阵。

到目前为止,我还无法正确访问矩阵中的元素,以便将它们应用到新的元素中。

ranNumsVec <- runif(1000, min = 100, max = 1000)

ranNumsVec <- round(ranNumsVec, digits = 0)


clusterSeqLengths <- matrix(data = ranNumsVec, nrow = 10, ncol = 100, 
                            byrow = FALSE, dimnames = NULL)

clusterSeqs <- matrix(data = NA, nrow = 10, ncol = 100, byrow = FALSE, dimnames = NULL)

^这些很好

使用这些功能,我试图将具有某些概率的字符应用于单独的矩阵。 (字符串矩阵),使得矩阵内的每个字符串由存储在上面的随机Nums Vec中的随机数之一确定。最后,我希望创建一个1000个ATGC序列的矩阵,长度为100到1000,如上所示。

lengthSmallString <- function(clusterSeqLengths)
                    clusterSeqs <- paste(sample("A", "C", "G", "T"),               c                   clusterSeqLengths,replace=TRUE ,prob=c(0.2, 0.55, 0.1,                .                   .15))

fillCharsToLength <- function(clusterSeqs)

                    clusterSeqs <- apply(clusterSeqs, 2, lengthSmallString, simplify = TRUE, USE.NAMES 
                    = FALSE)

我不完全确定如何正确迭代矩阵并将粘贴函数应用于一定长度的字符串。我试过一个for循环,但它没有让我走得很远

for(i=1:nume1(array) in clusterVectorNums)
{
  for(j in clusterVectorNums)
  {
    seqLength <- ranNumsVec[i,j]
    clusterSeqs[i,j] <- paste(sample(c("A", "C", "G", "T"),
    seqLength, replace=TRUE ,prob=c(0.2, 0.55, 0.1, 0.15)),
    collapse="")
  }
}

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,如果您在clusterSeqLengths[1,1]中有一个5,那么您期望在最终输出{{1}中将一系列长度为5的随机采样值c("A","C","G","T")作为单个字符串并且您想为clusterSeqs[1,1]中的每个单元格重复此过程。假设情况如此,您可以使用clusterSeqLengths

执行此操作

我修改了您提供的示例,以便问题的数量和大小更小,以便在我的帖子中显示结果。

apply

然后将set.seed(1) # initiliase RNG seed for reproducible results ranNumsVec <- runif(10, min = 0, max = 5) ranNumsVec <- round(ranNumsVec, digits = 0) clusterSeqLengths <- matrix(data = ranNumsVec, nrow = 5, ncol = 2, byrow = FALSE, dimnames = NULL) # first make a function which takes an n for # how long the sequence should be and returns the # relevant sequence f = function(n){ paste( sample(c("A", "C", "G", "T"), n, replace=TRUE ,prob=c(0.2, 0.55, 0.1, 0.15) ), collapse="") } clusterSeqLengths ## [,1] [,2] ## [1,] 1 4 ## [2,] 2 5 ## [3,] 3 3 ## [4,] 5 3 ## [5,] 1 0 # check it works on one value f(clusterSeqLengths[1,1]) ## [1] "C" apply一起使用,将函数index = c(1,2)应用于每个单元格

f
相关问题