[R] extracting rows of a dataframe

Berwin A Turlach berwin at maths.uwa.edu.au
Fri Dec 2 10:14:42 CET 2005


>>>>> "RH" == Robin Hankin <r.hankin at noc.soton.ac.uk> writes:

    RH> Three questions:

    RH> (1)  why is as.vector(a[2,-1]) not a vector?
Did you read the help file of as.vector() ?

> a <- data.frame(male=c(T,T,F),mass=c(1,4,3),height=c(4,3,2))
> a
   male mass height
1  TRUE    1      4
2  TRUE    4      3
3 FALSE    3      2
> x <- as.vector(a[2,-1])
> mode(x)
[1] "list"
> str(x)
`data.frame':	1 obs. of  2 variables:
 $ mass  : num 4
 $ height: num 3

Clearly you want:

> x <- as.vector(a[2,-1], mode="numeric")
> str(x)
 num [1:2] 4 3
> x
[1] 4 3


    RH> (2) How come setting names to NULL gives me bad weirdness?
> names(x) <- NULL
> str(x)
`data.frame':	1 obs. of  2 variables:
 $ : num 4
 $ : num 3
> x
  structure("4", class = "AsIs") structure("3", class = "AsIs")
2                              4                              3

With your "names(x)<-NULL" command you are wiping out the names of the
variables in your data frame.  Looking at print.data.frame(), the
answer to the so-called weirdness can presumably be found in
format.data.frame(). 

    RH> (3) Can I structure my dataframe in a better way, so that
    RH> this problem does not occur?
Not really, it's more a question of the appropriate use of
as.vector(). :-))

Cheers,

        Berwin

========================== Full address ============================
Berwin A Turlach                      Tel.: +61 (8) 6488 3338 (secr)   
School of Mathematics and Statistics        +61 (8) 6488 3383 (self)      
The University of Western Australia   FAX : +61 (8) 6488 1028
35 Stirling Highway                   
Crawley WA 6009                e-mail: berwin at maths.uwa.edu.au
Australia                        http://www.maths.uwa.edu.au/~berwin




More information about the R-help mailing list