Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an R function for finding the rows that contains a specific element in a matrix?

Tags:

r

matrix

rows

Let's say I have a 4x2 matrix.

x<- matrix(seq(1:8), 4)

That contains the following elements

1 5
2 6
3 7
4 8

For this specific example, let's say I want to remove the rows that contain a '2' or an '7' (without having to manually look in the matrix and remove them). How would I do this?

Here's something I came up with but it isn't doing what I want it to. I want it to return the row indices in the matrix that contain either a 2 or a 7.

remove<- which(2 || 7 %in% x)
x<- x[-remove,]

Can anyone help me figure this out?

like image 384
user1313954 Avatar asked Nov 10 '12 20:11

user1313954


2 Answers

x[-which(x == 2 | x == 7, arr.ind = TRUE)[,1],] 

is the simplest, most efficient way I can think of.

the single '|' checks if each element is 2 or 7 (which '||' won't do). arr.ind gives each position as a pair of coordinates, rather than the default single number. [,1] selects each row which has a 2 or 7.

Hope that helps :)

like image 55
Róisín Grannell Avatar answered Oct 15 '22 05:10

Róisín Grannell


As @Dirk said, which is the right function, here is my answer:

index <- apply(x, 1, function(a) 2 %in% a || 7 %in% a)
> index
[1] FALSE  TRUE  TRUE FALSE
x[index, ]
like image 3
liuminzhao Avatar answered Oct 15 '22 07:10

liuminzhao