dothermitian
dothermitian

Reputation: 239

Extract all column values row-wise by a particular row name in R

Suppose I have this matrix M:

           V1
B001E4KFG0 A3SGXH7AUHU8GW
B00813GRG4 A1D87F6ZCVE5NK
B00813GRG4 ABXLMWJIXXAIN

Now if I want to extract all column values by the rowname "B00813GRG4" what should I do. I tried M["B00813GRG4",] but it gives me only "A1D87F6ZCVE5NK" and not both "A1D87F6ZCVE5NK" and "ABXLMWJIXXAIN"

Upvotes: 5

Views: 530

Answers (1)

akrun
akrun

Reputation: 887881

We can use == to return a logical vector and then it can be used to subset the rows.

M[rownames(M)=='B00813GRG4',, drop=FALSE]
#            V1              
# B00813GRG4 "A1D87F6ZCVE5NK"
# B00813GRG4 "ABXLMWJIXXAIN" 

using the 'B00813GRG4' as row index will return only the first matching element similar to using match.

 M[match('B00813GRG4', rownames(M)),, drop=FALSE]
 #           V1              
 #B00813GRG4 "A1D87F6ZCVE5NK"

Upvotes: 3

Related Questions