[R] Access Rows in a Data Frame by Row Name
Anupam Tyagi
AnupTyagi at yahoo.com
Thu Sep 14 07:08:34 CEST 2006
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
More information about the R-help
mailing list