How to get row from R data.frame

后端 未结 5 621
温柔的废话
温柔的废话 2020-12-23 16:02

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)?

Specific

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-23 16:26

    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.

提交回复
热议问题