row.names()和attributes $ row.names有什么区别? [英] What's the difference between row.names() and attributes$row.names?

查看:109
本文介绍了row.names()和attributes $ row.names有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

row.names(iris)返回一个字符向量:

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

attributes(iris)$ row.names 返回整数向量:

> 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's the difference between them?

推荐答案


row.names()是通用便利函数。如评论中所指出的,数据框是具有(至少)属性名称 row.names class

row.names() is a generic convenience function. As pointed out in the comments, a data frame is a list object with (at least) the 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")

内部 structure(),将变量名称传递给参数。名称(不是名称)。

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

在基本包中,有两种用于通用函数的方法:

In the base package, there are two methods for the generic function:

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

默认方法是

函数(x)if(!is.null(dim(x)))行名(x) < br>
,而数据帧( row.names.data.frame )的方法是

函数( x)as.character(attr(x, row.names))

The default method is
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)。

If row names are not defined, row.names will be a vector with two elements, the first being NA, the second the negative number of rows (nrow(iris) is 150).

使用 row.names() attributes()是后者可以破坏数据帧:

One important difference between using row.names() and attributes() is that the latter can break the data frame:

> 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 的方法将无法正常工作:

Since the attribute was completely removed in b, methods for data.frame won't work properly anymore:

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

这篇关于row.names()和attributes $ row.names有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆