2017-06-22 69 views
0

所以目前,我有一個有8列和數行的數組引用人。我想使用apply函數根據另一列的值將一列的值更改爲1或0。使用r中的apply函數更改數組中的元素

我已經有這樣一個循環,它是

for(i in 1:nrow(OutComes)) { 
    if(OutComes[i,"Risk_Factor"] > 0.7) { 
    OutComes[i,"OnsetAge"] = 1 
    } else { 
    OutComes[i,"OnsetAge"] = 0 
    } 
} 

所以結局陣列具有稱爲其中每個人指定使用runif()的均勻隨機數「Risk_Factor」載體。如果此數字大於0.7,則「Onset Age」列中同一行中的元素會發生變化。

這將如何與應用函數一起工作? 我已經搜索,但無法找到任何幫助。

+0

看到這個鏈接,可能有助於[鏈接](http://petewerner.blogspot.in/2012/12/using-apply-sapply-lapply-in-r.html) –

回答

0

賦值是一個矢量化函數,所以不需要循環。

is_risky <- OutComes[,"Risk_Factor"] > 0.7 
OutComes[, "OnsetAge"] <- as.integer(is_risky) 
相關問題