2016-03-25 23 views
0

我試圖自己去解決這個問題,並在網上查詢如何做到這一點,但沒有直接的答案。基本上,我試圖刪除矩陣中超過3個字符的行。我的代碼只是刪除最後一行。第16-31行應該刪除。 i被迭代,但只刪除滿足條件的最後一列。但是,必須刪除更多行。我在這裏先向您的幫助表示感謝!在R中使用for循環時,如何在矩陣中刪除多行,而不僅僅是最後一行

setwd("~/Desktop/Rpractice") 

c <- c("1", "2", "3", "4", "5") 

combine <- function (x, y) {combn (y, x, paste, collapse = ",")} 

combination_mat <- as.matrix(unlist(lapply (1:length (c), combine, c))) 

for (i in length(combination_mat)) { 

    if (nchar(combination_mat[i]) > 3) { 

    newmat <- print(as.matrix(combination_mat[-i,])) 

    } 
} 

回答

1

你真的不需要一個循環來刪除那些行,比如你可以看看行超過3個字符,並刪除這些(請注意drop=FALSE參數,以保持數據的表格格式,而不是簡化到一個載體):

> combination_mat[nchar(combination_mat[, 1]) <= 3, , drop = FALSE] 
     [,1] 
[1,] "1" 
[2,] "2" 
[3,] "3" 
[4,] "4" 
[5,] "5" 
[6,] "1,2" 
[7,] "1,3" 
[8,] "1,4" 
[9,] "1,5" 
[10,] "2,3" 
[11,] "2,4" 
[12,] "2,5" 
[13,] "3,4" 
[14,] "3,5" 
[15,] "4,5" 
相關問題