0
    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

请帮忙

4

1 回答 1

2

如果我理解正确,您想根据您的调用结果创建一个零或一的矩阵。如果是这样,ifelse()可能会是一个更好的选择,因为它ifelse(C>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
于 2013-05-31T16:48:52.827 回答