How to get a row from R data.frame

I have data.frame with column headers.

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

In particular, my data.frame file

       Abc
     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 string equivalent to

> c(a=5, b=4.25, c=4.5) abc 5.0 4.25 4.5 
+79
r indexing dataframe
Aug 13 '09 at 1:44
source share
4 answers
 x[r,] 

where r is the string you are 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 indexing information.

+103
Aug 13 '09 at 2:23
source share

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 ) 
+10
Aug 20 '13 at 0:30
source share

Try:

 > d <- data.frame(a=1:3, b=4:6, c=7:9) > d abc 1 1 4 7 2 2 5 8 3 3 6 9 > d[1, ] abc 1 1 4 7 > d[1, ]['a'] a 1 1 
+4
Aug 13 '09 at 2:22
source share

If you do not know the line number, but know some values, you can use a subset

 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) ) subset(x, A ==5 & B==4.25 & C==4.5) 
+4
Aug 13 '09 at 7:56
source share



All Articles