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
请帮忙
答案 0 :(得分: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