Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R应用错误:';X';必须有名字_R_Dataframe - Fatal编程技术网

R应用错误:';X';必须有名字

R应用错误:';X';必须有名字,r,dataframe,R,Dataframe,“apply”文档提到“如果'X'命名了dimnames,那么它可以是选择维度名称的字符向量。”我只想对data.frame中的特定列使用apply。我可以使用dimnames功能来执行此操作吗 我意识到我可以将()X子集只包含感兴趣的列,但我想更好地理解“named dimnames” 下面是一些示例代码: > x <- data.frame(cbind(1,1:10)) > apply(x,2,sum) X1 X2 10 55 > apply(x,c('X2'),s

“apply”文档提到“如果'X'命名了dimnames,那么它可以是选择维度名称的字符向量。”我只想对data.frame中的特定列使用apply。我可以使用dimnames功能来执行此操作吗

我意识到我可以将()X子集只包含感兴趣的列,但我想更好地理解“named dimnames”

下面是一些示例代码:

> 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
>x应用(x,2,总和)
X1-X2
10 55
>应用(x,c('X2'),总和)
apply(x,c(“X2”),sum中出错:'x'必须有命名的dimnames
>dimnames(x)
[[1]]
[1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"
[[2]]
[1] “X1”“X2”
>姓名(x)
[1] “X1”“X2”
>名称(dimnames(x))
无效的

问题在于,由于某种原因,您无法直接操作
x
的DIMNAME,并且
x
将被强制为不保留命名DIMNAME的矩阵

解决方案是首先强制使用矩阵,然后命名dimnames,然后使用
apply()

>X str(X)
数字[1:10,1:2]1。。。
-属性(*,“dimnames”)=2个列表
..$:chr[1:10]“1”“2”“3”“4”。。。
..$:chr[1:2]“X1”“X2”
>dimnames(X)str(X)
数字[1:10,1:2]1。。。
-属性(*,“dimnames”)=2个列表
..$C1:chr[1:10]“1”“2”“3”“4”。。。
..$C2:chr[1:2]“X1”“X2”
>应用(X,“C1”,平均值)
1   2   3   4   5   6   7   8   9  10 
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 
>rowMeans(X)
1   2   3   4   5   6   7   8   9  10 
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5

如果我理解正确,您希望仅在某些列上使用apply。这不是命名的dimnames所能实现的。矩阵或data.frame上的apply函数始终应用于所有行或所有列。命名的dimnames允许您选择按名称使用行或列,而不是“普通”的
1
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

m@Tommy指出,通过这种方法,你似乎不能做你想做的事情,你只能命名应用了
FUN
的维度。我把答案贴出来是为了解释你的Q中被命名的dimnames是什么意思。
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
n <- c("A","C")
apply(m[,n], 2, sum)
# A  C 
#10 42