Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get row from R data.frame

I have a data.frame with column headers.

How can I get a specific row from the data.frame as a list (with the column headers as keys for the list)?

Specifically, my data.frame is

       A    B    C     1 5    4.25 4.5     2 3.5  4    2.5     3 3.25 4    4     4 4.25 4.5  2.25     5 1.5  4.5  3 

And I want to get a row that's the equivalent of

> c(a=5, b=4.25, c=4.5)   a   b   c  5.0 4.25 4.5  
like image 211
Will Glass Avatar asked Aug 13 '09 01:08

Will Glass


People also ask

How do I get rows from a Dataframe in R?

To get a specific row of a matrix, specify the row number followed by a comma, in square brackets, after the matrix variable name. This expression returns the required row as a vector.

How do I select a specific row in R studio?

If you'd like to select multiple rows or columns, use a list of values, like this: students[c(1,3,4),] would select rows 1, 3 and 4, students[c("stu1", "stu2"),] would select rows named stu1 and stu2 .


2 Answers

x[r,] 

where r is the row you're interested in. Try this, for example:

#Add your data x <- structure(list(A = c(5,    3.5, 3.25, 4.25,  1.5 ),                      B = c(4.25, 4,   4,    4.5,   4.5 ),                     C = c(4.5,  2.5, 4,    2.25,  3   )                ),                .Names    = c("A", "B", "C"),                class     = "data.frame",                row.names = c(NA, -5L)      )  #The vector your result should match y<-c(A=5, B=4.25, C=4.5)  #Test that the items in the row match the vector you wanted x[1,]==y 

This page (from this useful site) has good information on indexing like this.

like image 131
Matt Parker Avatar answered Sep 27 '22 23:09

Matt Parker


Logical indexing is very R-ish. Try:

 x[ x$A ==5 & x$B==4.25 & x$C==4.5 , ]  

Or:

subset( x, A ==5 & B==4.25 & C==4.5 ) 
like image 40
IRTFM Avatar answered Sep 28 '22 01:09

IRTFM