Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

nrow(matrix1) is 400000

>Solution :

You can simply extract the rows satisfying your condition:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading