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?
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 :)
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, ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With