gpt4 book ai didi

R:行名、列名、暗号和名称适用

转载 作者:行者123 更新时间:2023-12-04 11:09:09 30 4
gpt4 key购买 nike

我想使用 apply 来跨越矩阵的行,并且我想在我的函数中使用当前行的行名。好像不能用rownames , colnames , dimnamesnames直接在函数内部。我知道我可以根据 this question 中的信息创建一个解决方法。 .

但我的问题是 apply在它的第一个参数中处理数组的行名和列名,并将名称分配给在 apply 调用的函数内创建的对象。 ?这似乎有点不一致,我希望通过以下示例来说明。它设计成这样有什么原因吗?

# Toy data
m <- matrix( runif(9) , nrow = 3 )
rownames(m) <- LETTERS[1:3]
colnames(m) <- letters[1:3]
m
a b c
A 0.5092062 0.3786139 0.120436569
B 0.7563015 0.7127949 0.003358308
C 0.8794197 0.3059068 0.985197273

# These return NULL
apply( m , 1 , FUN = function(x){ rownames(x) } )
NULL
apply( m , 1 , FUN = function(x){ colnames(x) } )
NULL
apply( m , 1 , FUN = function(x){ dimnames(x) } )
NULL

# But...
apply( m , 1 , FUN = function(x){ names(x) } )
A B C
[1,] "a" "a" "a"
[2,] "b" "b" "b"
[3,] "c" "c" "c"
# This looks like a column-wise matrix of colnames, with the rownames of m as the column names to me

# And further you can get...
n <- apply( m , 1 , FUN = function(x){ names(x) } )
dimnames(n)
[[1]]
NULL

[[2]]
[1] "A" "B" "C"

# But you can't do...
apply( m , 1 , FUN = function(x){ n <- names(x); dimnames(n) } )
NULL

我只是想了解应用内部会发生什么?非常感谢。

最佳答案

我认为您的困惑源于 apply不将数组(或矩阵)传递给 FUN 中指定的函数.

它依次传递矩阵的每一行。每行本身“仅”是一个(命名的)向量:

> m[1,]
a b c
0.48768161 0.61447934 0.08718875

所以你的函数只有这个命名向量可以使用。

对于您的中间示例,如 apply 中所述:

If each call to FUN returns a vector of length n, then apply returns an array of dimension c(n, dim(X)[MARGIN]) if n > 1. If n equals 1, apply returns a vector if MARGIN has length 1 and an array of dimension dim(X)[MARGIN] otherwise.



所以 function(x) names(x)为每一行返回一个长度为 3 的向量,因此最终结果是您看到的矩阵。但是该矩阵是在 apply 的末尾构建的函数,对 FUN 的结果单独应用于每一行。

关于R:行名、列名、暗号和名称适用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15229199/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com