2013-05-31 75 views
0
C<-c(1,3,4,5,5,5,6,4,6)   
    result<-which(C>5,arr.in=TRUE) 

在條件爲真時給出索引。通過找到的矢量索引填充矩陣索引

它給7和9通過改變Ç任意然後最終結果的值是真實

我要求這些指數是在矩陣存儲爲1或0 例如,如果我重複這個代碼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 

請幫

回答

2

如果我理解正確的話,你想創建基於您的其中調用的結果0或1的矩陣。如果是這樣,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 
+0

非常感謝親愛的。你能解釋這個代碼是如何工作的嗎?我不明白爲什麼使用函數(x),1:10是什麼意思,do.call的目的是什麼。在此先感謝 –

+0

當然,我會編輯更多的細節的帖子。 – David

+0

好的,我添加了一些希望更清晰的評論。如果對do.call()或lapply()的工作方式仍然存在困惑,那麼很多其他線程都應該能夠解決這個問題,例如:http://stackoverflow.com/questions/3505701/r-grouping-functions -sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega和http://stackoverflow.com/questions/10801750/whats-the-difference-between-lapply-and-do-call -in-R – David