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

标签 r function base apply

我想使用 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/

相关文章:

PHP将所有参数作为数组获取?

python - 从列表中的各个字符串中删除重复项

C Base128 函数

javascript - 如何在 JavaScript 中将十进制转换为十六进制

arrays - 有效地计算 R 中 3d 数组的行总和

r - 修改时复制;运行此代码时会发生什么? x <- 列表(1 :10); x[[2]] <- x

r - 将 data.table 的行值转换为传递相应行值的超链接

r - 如何在 R 中存储图形(来自 igraph 包)?

c++ - 我的 C++ 函数不断出现调试错误。我不确定我做错了什么

Python:为什么 0.01.as_integer_ratio() 返回 5764607523034235/576460752303423488