R为什么按行名称和组件名称列出数据框中的元素返回NA?

时间:2022-07-04 09:14:03

I create a data frame dfrm with one column, and set the row names as so:

我用一列创建一个数据框dfrm,并将行名设置为:

v1 = c(1,2,3)
dfrm <- data.frame(v1)
row.names(dfrm) <- c("AD","BP","CD")

dfrm
   v1
AD  1
BP  2
CD  3

I can access elements by row name and index:

我可以按行名和索引访问元素:

dfrm$v1[1]
[1] 1

I can access elements by row name and component name in quotes:

我可以按引号中的行名和组件名访问元素:

dfrm["AD","v1"]
[1] 1

But why can't I access elements by row name and component name?

但为什么我不能按行名和组件名访问元素?

dfrm$v1["AD"]
[1] NA

1 个解决方案

#1


5  

The answer is that vectors don't have rownames although they can have names.

答案是矢量没有rownames,尽管它们可以有名字。

When you access a column as a list item, R does not take the additional step of passing along the rownames to the names of the vector:

当您将列作为列表项访问时,R不会采取额外的步骤将rownames传递给向量的名称:

> dfrm$v1
[1] 1 2 3
> dfrm[["v1"]]
[1] 1 2 3
> dfrm[,"v1"]
[1] 1 2 3
> dfrm[,1]
[1] 1 2 3
> names(dfrm$v1)
NULL

Note that this is probably a good thing, as the cases where this is helpful are limited, and the overhead to copy the names every time a data.frame has a column pulled out likely not worth it.

请注意,这可能是一件好事,因为有用的情况是有限的,每次data.frame有一个列被拔出时复制名称的开销可能不值得。

If you want to copy them yourself:

如果您想自己复制它们:

> vone <- dfrm$v1
> names(vone) <- rownames(dfrm)
> vone
AD BP CD 
 1  2  3 

#1


5  

The answer is that vectors don't have rownames although they can have names.

答案是矢量没有rownames,尽管它们可以有名字。

When you access a column as a list item, R does not take the additional step of passing along the rownames to the names of the vector:

当您将列作为列表项访问时,R不会采取额外的步骤将rownames传递给向量的名称:

> dfrm$v1
[1] 1 2 3
> dfrm[["v1"]]
[1] 1 2 3
> dfrm[,"v1"]
[1] 1 2 3
> dfrm[,1]
[1] 1 2 3
> names(dfrm$v1)
NULL

Note that this is probably a good thing, as the cases where this is helpful are limited, and the overhead to copy the names every time a data.frame has a column pulled out likely not worth it.

请注意,这可能是一件好事,因为有用的情况是有限的,每次data.frame有一个列被拔出时复制名称的开销可能不值得。

If you want to copy them yourself:

如果您想自己复制它们:

> vone <- dfrm$v1
> names(vone) <- rownames(dfrm)
> vone
AD BP CD 
 1  2  3