João Carvalho
João Carvalho

Reputation: 159

Remove rows of a Matrix in R according to a condition

Imagine you have the following matrix in R:

      [,1]   [,2] [,3] [,4] [,5]
[1,]  "A/B"    3    4    5    7
[2,]  "A/C"    8    6    7    7
[3,]  "A/B/C"  8    8    5    4

What is the easiest way to remove the rows where I have more than two letters on the first column? I think the rationale should be something like:

if nchar(matrix[,1]!=3) then remove that row

But I don't know how to code this. Any help would be appreciated! Thanks

Upvotes: 0

Views: 245

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521249

Convert your matrix to a data frame, and then use grepl to check for a matching pattern of three or more letter:

df <- df[!grepl("\\w/\\w/\\w.*", df$letters),]

enter image description here

Demo

Some of the suggestions in the comments above might also work for you, but a regex based solution has the added benefit that it is robust, and can be easily changed if your requirements change at some point in the future.

Upvotes: 1

Related Questions