【问题标题】:Filling matrix index by vector index found by which用找到的向量索引填充矩阵索引
【发布时间】:2013-05-27 13:12:23
【问题描述】:
    C<-c(1,3,4,5,5,5,6,4,6)         
    result<-which(C>5,arr.in=TRUE)

当条件为真时给出索引。

7 和 9 为真

我要求这些索引以 1 或 0 的形式存储在矩阵中。 例如,如果我通过任意更改 C 的值来迭代此代码 5 次,那么矩阵的最终结果将是

    0 0 0 0 0 0 1 0 1
    1 0 0 1 0 0 0 1 0
    0 0 0 0 1 0 0 1 1
    1 1 1 0 0 0 1 1 0
    0 0 0 0 0 0 1 0 0

请帮忙

【问题讨论】:

    标签: r matrix


    【解决方案1】:

    如果我理解正确,您想根据调用的结果创建一个由 0 或 1 组成的矩阵。如果是这样,ifelse() 可能是更好的选择,因为ifelse(C&gt;5,0,1) 返回您想要的确切向量,因此您需要做的就是将所有这些向量组合在一起。你没有提供你的“C”向量列表,所以我写了一个快速函数来生成一些向量来向你展示它是如何工作的:

    > #function to generate a "C" vector
    > makeC <- function(x){
    +   set.seed(x)
    +   round(runif(10,0,10))
    + }
    > 
    > #create a list of "C" vectors
    > c.list <- lapply(1:5,makeC)
    > #look at list of your vectors that you want binary indices
    > c.list
    [[1]]
     [1] 3 4 6 9 2 9 9 7 6 1
    
    [[2]]
     [1] 2 7 6 2 9 9 1 8 5 5
    
    [[3]]
     [1] 2 8 4 3 6 6 1 3 6 6
    
    [[4]]
     [1] 6 0 3 3 8 3 7 9 9 1
    
    [[5]]
     [1]  2  7  9  3  1  7  5  8 10  1
    
    > #make a list of your binary indices
    > c.bin.list <- lapply(c.list,function(x) ifelse(x>5,1,0))
    > #lookat your list of binary indices
    > c.bin.list
    [[1]]
     [1] 0 0 1 1 0 1 1 1 1 0
    
    [[2]]
     [1] 0 1 1 0 1 1 0 1 0 0
    
    [[3]]
     [1] 0 1 0 0 1 1 0 0 1 1
    
    [[4]]
     [1] 1 0 0 0 1 0 1 1 1 0
    
    [[5]]
     [1] 0 1 1 0 0 1 0 1 1 0
    
    > #combine all of your binary indice vectors into a matrix with rbind()
    > c.bin <- do.call(rbind,c.bin.list)
    > #look at your matrix of binary indices
    > c.bin
         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
    [1,]    0    0    1    1    0    1    1    1    1     0
    [2,]    0    1    1    0    1    1    0    1    0     0
    [3,]    0    1    0    0    1    1    0    0    1     1
    [4,]    1    0    0    0    1    0    1    1    1     0
    [5,]    0    1    1    0    0    1    0    1    1     0
    > #this can also be collapsed into a one-liner
    > do.call(rbind,lapply(1:5, function(x) ifelse(makeC(x)>5,1,0)))
         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
    [1,]    0    0    1    1    0    1    1    1    1     0
    [2,]    0    1    1    0    1    1    0    1    0     0
    [3,]    0    1    0    0    1    1    0    0    1     1
    [4,]    1    0    0    0    1    0    1    1    1     0
    [5,]    0    1    1    0    0    1    0    1    1     0
    

    【讨论】:

    • 非常感谢亲爱的。你能解释一下这段代码是如何工作的吗?我不明白为什么要使用 function(x),1:10 是什么意思,do.call 的目的是什么。提前致谢
    • 好的,我添加了一些希望更清晰的 cmets。如果仍然对 do.call() 或 lapply() 的工作方式感到困惑,那么应该有许多其他线程能够解决这个问题,例如:stackoverflow.com/questions/3505701/…stackoverflow.com/questions/10801750/…
    猜你喜欢
    • 2014-11-19
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    相关资源
    最近更新 更多