r - 为什么将行名更改为相同时相同的数据帧会变得不同

标签 r dataframe rowname

我在玩一些数据帧时遇到了一个奇怪的行为:当我创建两个相同的数据帧 a,b,然后交换它们的行名时,它们并不相同:

rm(list=ls())

a <- data.frame(a=c(1,2,3),b=c(2,3,4))
b <- a
identical(a,b)
#TRUE

identical(rownames(a),rownames(b))
#TRUE

rownames(b) <- rownames(a)

identical(a,b)
#FALSE

谁能重现/解释原因?

最佳答案

诚然,这有点令人困惑。从 ?data.frame 开始,我们看到:

If row.names was supplied as NULL or no suitable component was found the row names are the integer sequence starting at one (and such row names are considered to be ‘automatic’, and not preserved by as.matrix).

所以最初 ab 每个都有一个名为 row.names 的属性,它是整数:

> str(attributes(a))
List of 3
 $ names    : chr [1:2] "a" "b"
 $ row.names: int [1:3] 1 2 3
 $ class    : chr "data.frame"

但是 rownames() 返回一个字符向量(与 dimnames() 一样,实际上是一个字符向量列表,在后台调用)。因此,在重新分配行名称后,您最终得到:

> str(attributes(b))
List of 3
 $ names    : chr [1:2] "a" "b"
 $ row.names: chr [1:3] "1" "2" "3"
 $ class    : chr "data.frame"

关于r - 为什么将行名更改为相同时相同的数据帧会变得不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42515753/

相关文章:

r - 使用 R 连接到 Youtube Analytics API

python - Pandas 0.23 groupby 和 pct 更改未返回预期值

r - 如何获取特定名称的行索引号?

r - 从三个数据框中一一组合列

r - 更改 data.frame 中的单行名称

删除 gridExtra::tableGrob 中的行名

r - 如何解决 R 中的 "could not find function vapply"错误?

r - 海洋起始年份误差 R

r - 在 R 中查找给定数据的 "row wise" "Mode"

python - 为什么Python print 会打印一些表情符号而不打印其他表情符号?