2009-08-13 8 views
81

Ho un data.frame con intestazioni di colonna.Come ottenere una riga da R data.frame

Come è possibile ottenere una riga specifica da data.frame come elenco (con le intestazioni di colonna come chiavi per l'elenco)?

In particolare, il mio data.frame è

 
     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 

e voglio ottenere una riga che è l'equivalente di

> c(a=5, b=4.25, c=4.5) 
    a b c 
5.0 4.25 4.5 

risposta

104
x[r,] 

dove r è la riga che ti interessa. Prova questo, ad esempio:

#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 (da this useful site) ha buone informazioni su indicizzazione come questo.

4

Prova:

> 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 
4

Se non si conosce il numero di riga, ma fai conoscere alcuni valori quindi è possibile utilizzare sottoinsieme

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) 
+0

vuoi dire questo, invece? sottoinsieme (x, A == 5 && B == 4,25 && C == 4,5) – momeara

+0

No, avrebbe dovuto essere: 'sottoinsieme (x, A == 5 & B == 4,25 & C == 4,5)' –

10

indicizzazione logica è molto R-ish. Prova:

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

Oppure:

subset(x, A ==5 & B==4.25 & C==4.5)