在 R 中使用 for 循环时,如何删除矩阵中的多行,而不仅仅是最后一行
How to delete more than one row in a matrix, not just last row, when using a for loop in R
我试着自己解决这个问题,并在网上查找了如何做到这一点,但没有直接的答案。基本上,我试图删除矩阵中超过 3 个字符的行。我的代码只删除最后一行。第 16-31 行应删除。 i
被迭代,但只删除满足条件的最后一列。但是,必须删除更多行。提前感谢您的帮助!
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,]))
}
}
您确实不需要循环来删除这些行,例如,您可以查找超过 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"
我试着自己解决这个问题,并在网上查找了如何做到这一点,但没有直接的答案。基本上,我试图删除矩阵中超过 3 个字符的行。我的代码只删除最后一行。第 16-31 行应删除。 i
被迭代,但只删除满足条件的最后一列。但是,必须删除更多行。提前感谢您的帮助!
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,]))
}
}
您确实不需要循环来删除这些行,例如,您可以查找超过 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"