R套用错误:“ X”必须具有命名的名字 [英] R apply error: 'X' must have named dimnames

查看:106
本文介绍了R套用错误:“ X”必须具有命名的名字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应用文档中提到在X命名为dimname的地方,它可以是选择维名称的字符向量。我只想在data.frame上仅对特定列使用apply。我可以使用dimnames功能来做到这一点吗?

The "apply" documentation mentions that "Where 'X' has named dimnames, it can be a character vector selecting dimension names." I would like to use apply on a data.frame for only particular columns. Can I use the dimnames feature to do this?

我意识到我可以将subset()X只包含感兴趣的列,但是我想了解命名的dimnames

I realize I can subset() X to only include the columns of interest, but I want to understand "named dimnames" better.

下面是一些示例代码:

> x <-  data.frame(cbind(1,1:10))
> apply(x,2,sum)
X1 X2
10 55
> apply(x,c('X2'),sum)
Error in apply(x, c("X2"), sum) : 'X' must have named dimnames
> dimnames(x)
[[1]]
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"

[[2]]
[1] "X1" "X2"
> names(x)
[1] "X1" "X2"
> names(dimnames(x))
NULL


推荐答案

如果我对您的理解正确,那么您只想在某些列上使用Apply。这不是名叫dimnames的功能。矩阵或data.frame上的apply函数始终适用于 all 行或 all 列。命名的dimnames允许您选择按名称使用行或列,而不使用普通 1 2

If I understand you correctly, you would like to use apply only on certain columns. This is not what named dimnames would accomplish. The apply function on a matrix or data.frame always applies to all the rows or all the columns. The named dimnames allows you to choose to use rows or columns by name instead of the "normal" 1 and 2:

m <- matrix(1:12,4, dimnames=list(foo=letters[1:4], bar=LETTERS[1:3]))
apply(m, "bar", sum)  # Use "bar" instead of 2 to refer to the columns

但是,如果您有要应用的列名,可以先选择那些列来完成:

However if you have the column names you'd like to apply to, you could do it by first selecting only those columns:

n <- c("A","C")
apply(m[,n], 2, sum)
# A  C 
#10 42 

命名的dimnames是副作用,因为dimnames存储为矩阵数组的 dimnames属性中的列表。列表的每个组件都对应一个维度,可以命名。对于多维数组,这可能更有用...

Named dimnames is a side-effect of that dimnames are stored as a list in the "dimnames" attribute in a matrix or array. Each component of the list corresponds to one dimension and can be named. This is probably more useful for multidimensional arrays...

对于 data.frame ,没有假名 属性。 data.frame 本质上是一个列表,因此列表的名称属性对应于列名称,另外一个 row.names属性对应于行名称。因此,没有地方可以存储暗角名称的名称(当然,暗角名称可以具有额外的属性,但没有)。当您在data.frame上调用假名函数时,它只是根据 row.names和 names属性创建一个列表。

For a data.frame, there is no "dimnames" attribute. A data.frame is essentially a list, so the list's "names" attributes corresponds to the column names, and an extra "row.names" attribute corresponds to the row names. Because of this, there is no place to store the names of the dimnames (they could have an extra attribute for that of course, but they didn't). When you call the dimnames function on a data.frame, it simply creates a list from the "row.names" and "names" attributes.

这篇关于R套用错误:“ X”必须具有命名的名字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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