2012-10-30 21 views
-1

基本上我有一個矩陣,並用在其予想追加一個「1」發送給列表行,否則追加一個「0」檢查,如果事情是在每一行中(行長度> 1)

的代碼如下:

is.there.A <- function(a,b,c,d,e) { 

    library(combinat) 
    x <- c(a,b,c,d,e) 
    matrix <- matrix(combn(x,3), ncol=3, byrow=T) 
    row <- nrow(matrix) 
    list <- list() 

    for (i in seq(row)) { 

    if (matrix[i,] %in% "A") {c(list, "1")} 

    else {c(list, "0")} 

    print(list) 

    } 

} 

但它不起作用,這顯示出來。

警告消息:

1:在如果(矩陣[I,]%以% 「A」){:

狀況已經長度> 1且僅第一個元素將被用來

的問題是如何克服這個目標實現

+0

你爲什麼不使用ifelse?你也有百分之%向後。 –

回答

1

你能避免你顯式循環功能的預分配,然後填寫。

避免命名與功能名稱的對象(如cmatrixlist

1

你的意思是測試"A" %in% matrix[i,],而不是周圍的其他方式。但是,請注意

row <- nrow(matrix) 
list <- list() 
for (i in seq(row)) { 
    if ("A" %in% matrix[i,]) {c(list, "1")} 
    else {c(list, "0")} 
} 

可以改寫

rowSums(matrix == "A") > 0 

它返回邏輯值的矢量(TRUE/FALSE),這是你的函數的最合適的輸出。但是,如果你真的需要的「1」或「0」的列表,你可以如下把它包裝:

as.list(ifelse(rowSums(matrix == "A") > 0, "1", "0")) 

另外請注意,這是一個糟糕的主意,因爲它也是名字來命名一個對象matrix通過使用apply

is.there.A <- function(a,b,s,d,e) { 

    library(combinat) 
    x <- c(a,b,s,d,e) 
    .matrix <- matrix(combn(x,3), ncol=3, byrow=T) 

    any_A <- apply(.matrix, 1, `%in%`, x = 'A') 
    as.list(as.numeric(any_A)) 

} 

內不增長的對象for循環,在R.

相關問題