Re: [R] Access Rows in a Data Frame by Row Name

From: Anupam Tyagi <AnupTyagi_at_yahoo.com>
Date: Thu 14 Sep 2006 - 05:08:34 GMT

I hope this helps.

> x <- data.frame(a=1:5, b=6:10, d=11:15)
> x
  a b d
1 1 6 11
2 2 7 12
3 3 8 13
4 4 9 14
5 5 10 15
> # access row with name "a". This does not work.
> x$a

[1] 1 2 3 4 5
> # access column with name "d"
> x$d

[1] 11 12 13 14 15
> x$row.names

NULL
> attributes(x)

$names
[1] "a" "b" "d"

$row.names
[1] "1" "2" "3" "4" "5"

$class
[1] "data.frame"

> x$row.names()

Error: attempt to apply non-function
> row.names(x)

[1] "1" "2" "3" "4" "5"
> # access first row by index
> x[1,]

  a b d
1 1 6 11
> # access first row by "name"
> x["1",]

  a b d
1 1 6 11
> # access second row by "name"
> x["2",]

  a b d
2 2 7 12
> # change row names to alphabets.
> row.names(x) <- c("a","b","c","d","e")
> row.names(x)

[1] "a" "b" "c" "d" "e"
> # access second row by old name. Does not work because of name change.
> Why this does not give error: "2" row name does not exist?
> x["2",]

    a b d
NA NA NA NA
> # access third row by "name".
> x["c",]

  a b d
c 3 8 13



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu Sep 14 15:13:23 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 14 Sep 2006 - 05:30:06 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.