R: Append matrix rows if condition is met

I loop through a matrix and I would like to append a matrix row to another empty matrix if a specific condition is met. How do I do this without getting problems with the different indexes?
I had this code, but my dataset is very large, so I get problems in the implementation

for (i in 1:length(matrix1)) {
    if ((substr(matrix1[i,1],6,7) == '02') == TRUE) {
        for (j in 1:nrow(matrix2)) {
            matrix2[j,] <- matrix1[i,]
        }
    }
}

Is there a more efficient solution?

dput(matrix1[1]) is c("271", "269", "274", "278", "293", "270", "274", "274", "275", "271", "2018-01-03_0445")

nrow(matrix1) is 400000

>Solution :

You can simply extract the rows satisfying your condition:

matrix2 <- matrix1[substr(matrix1[, 1], 6, 7) == '02', ]

Leave a Reply