STATEN_star
STATEN_star

Reputation: 187

Deleting rows in matrix

I have a matrix, which could look like this:

have=rbind(matrix(c(1,1,1,1,2,2,2,2,3,3,3,3),ncol=3),c(5,5,5),c(5,5,5),c(5,5,5),c(1,1,1),c(1,1,1))

      [,1] [,2] [,3]
 [1,]    1    2    3
 [2,]    1    2    3
 [3,]    1    2    3
 [4,]    1    2    3
 [5,]    5    5    5
 [6,]    5    5    5
 [7,]    5    5    5
 [8,]    1    1    1
 [9,]    1    1    1

I want to delete rows, if they only appear say 1 or two times. Ideally, I want it to be user-specificed, so if the row only appears N times or less it should be deleted. So, if N=2 then it should delete the last two rows, because they only appear two times:

want=rbind(matrix(c(1,1,1,1,2,2,2,2,3,3,3,3),ncol=3),c(5,5,5),c(5,5,5),c(5,5,5))

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    2    3
[3,]    1    2    3
[4,]    1    2    3
[5,]    5    5    5
[6,]    5    5    5
[7,]    5    5    5

On the other hand, if N=3, then it should return:

want_2=rbind(matrix(c(1,1,1,1,2,2,2,2,3,3,3,3),ncol=3))

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    2    3
[3,]    1    2    3
[4,]    1    2    3

Upvotes: 3

Views: 133

Answers (2)

thothal
thothal

Reputation: 20409

Here's how I would do that:

Code

code <- apply(have, 1, paste, collapse = "\t")
rl <- rle(code)
have[code %in% rl$values[rl$lengths > 2], ]
#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]    1    2    3
# [3,]    1    2    3
# [4,]    1    2    3
# [5,]    5    5    5
# [6,]    5    5    5
# [7,]    5    5    5

Explanation

  1. First, you get the string representation of each row via apply
  2. Then you calculate how often each token appears in the whole matrix (via rle)
  3. Then you select only those rows which do appear more than 2 times

Upvotes: 1

Julius Vainora
Julius Vainora

Reputation: 48251

rowRemove <- function(x, n) {
  oc <- apply(x, 1, paste, collapse = "\r")
  x[table(oc)[oc] > n, ]
}
rowRemove(have, 3)
#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]    1    2    3
# [3,]    1    2    3
# [4,]    1    2    3

Upvotes: 5

Related Questions