What is the difference between row.names () and $ row.names attributes?

row.names(iris) returns a character vector:

> row.names(head(iris))
[1] "1" "2" "3" "4" "5" "6"

and attributes(iris)$row.namesreturns an integer vector:

> attributes(head(iris))$row.names
[1] 1 2 3 4 5 6

I am surprised that these 2 functions do not return the same thing. What is the difference between the two?

+4
source share
1 answer

row.names()- general convenience function. As noted in the comments, a data frame is a list object with (at least) attributes "names", "row.names"and "class".

> dput(data.frame("x" = c(1, 2, 3)))
structure(list(x = c(1, 2, 3)), .Names = "x", row.names = c(NA, -3L), class = "data.frame")

Inside, structure()variable names are passed to the .Names(not names) argument .

There are two methods in the base package for a generic function:

> methods(row.names)
[1] row.names.data.frame row.names.default

The default method is used function (x) if (!is.null(dim(x))) rownames(x)
while the method for data frames ( row.names.data.frame) is function (x) as.character(attr(x, "row.names"))

, row.names , NA, - (nrow(iris) 150).

row.names() attributes() , :

> a <- b <- data.frame("x" = c("obs1" = 4, "obs2" = 6, "obs3" = -1))
> a
      x
obs1  4
obs2  6
obs3 -1
> row.names(a) <- NULL
> a
   x
1  4
2  6
3 -1
> attributes(b)$row.names <- NULL
> b
[1] x
<0 rows> (or 0-length row.names)

b, data.frame :

> str(b)
'data.frame':   0 obs. of  1 variable:
 $ x: num  4 6 -1
0

All Articles