tags:

views:

4088

answers:

3

I have a dataframe with column headers.

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

Specifically, my dataframe 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
A: 

Try:

> d <- data.frame(a=1:3, b=4:6, c=7:9)

> d
  a b c
1 1 4 7
2 2 5 8
3 3 6 9

> d[1, ]
  a b c
1 1 4 7

> d[1, ]['a']
  a
1 1
ars
+3  A: 
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.

Matt Parker
I'm just assuming that the 4.5 in the c() is supposed to be 4.25 like in the data.
Matt Parker
fixed the question - thanks much.
Will Glass
== doesn't test for equivalence - it's a vectorised test of equality. A single row of a data frame is not the same thing as a named vector (for one thing you can use $ with a data frame).
hadley
Thanks, Hadley - need to be more careful with my phrasing (and, frankly, learn more about what exactly some of those operators do). I updated my posting to reflect your point.
Matt Parker
A: 

If you don't know the row number, but do know some values then you can use 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)
Thierry
momeara