martamarta
martamarta

Reputation: 1

How do you extract multiple elements by their name in matrix or list in R?

I have created a matrix in which I have many elements in 3 columns called: example

SYMBOL  NAME     FUNCTION
c       cat      pet
d       dog      first aid
b       bird     song
m       monkey   forest

etc

I have a an object done like this : c("c","d"). My objective is to look for the presence of my multiples objects: "c" and "d" and to obatin the entire row, something like: "c" "cat" "pet" "d" "dog" "fist aid". I have tried with functions "which" to know the entire row of a single element but I am not able to look for various elements because if I do which (matrix == "c") answer: [1] 1 and then matrix[1, ] but this is sooo long and I cannot look for multiple elements. Any help please? thanks

Upvotes: 0

Views: 129

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545518

There’s no need for which. Conversely, since you want to return multiple rows based on multiple IDs, you need to use the %in% operator instead of equality comparison via ==.

The following code will return the matching rows from a matrix named mat:

mat[mat[, "SYMBOL"] %in% c("c", "d"), ]

Upvotes: 1

Related Questions