r - 如何将矩阵列作为参数传递给 .apply 函数?
问题描述
我想一次将多个参数传递给一个函数,其中这些参数是包含在这样一个矩阵中的向量:
> head(M, 3)
[,1] [,2] [,3]
[1,] 1.3709584 1.304870 -0.3066386
[2,] -0.5646982 2.286645 -1.7813084
[3,] 0.3631284 -1.388861 -0.1719174
例如,考虑cor()
以下行给了我想要的东西,但我不想嵌套。
> sapply(1:3, function(x) sapply(1:3, function(y, ...) cor(M[, x], M[, y])))
[,1] [,2] [,3]
[1,] 1.0000000 -0.3749289 0.4400510
[2,] -0.3749289 1.0000000 -0.1533438
[3,] 0.4400510 -0.1533438 1.0000000
我认为outer()
会成为候选人,因为:
> outer(1:3, 1:3, function(x, y) x + y)
[,1] [,2] [,3]
[1,] 2 3 4
[2,] 3 4 5
[3,] 4 5 6
但
corFun <- function(x, y) cor(M[, x], M[, y])
outer(1:3, 1:3, corFun)
不会工作。mapply(corFun, M[, 1], M[, 2])
尝试也不会奏效。
我想做xFun(corFun, M, arg)
甚至更好地xFun(cor, M, arg)
给出(如上):
[,1] [,2] [,3]
[1,] 1.0000000 -0.3749289 0.4400510
[2,] -0.3749289 1.0000000 -0.1533438
[3,] 0.4400510 -0.1533438 1.0000000
在哪里arg <- combn(1:3, 2)
或arg <- t(expand.grid(1:3, 1:3))
。
一般来说,我想知道是否有一个现有的基本 R 函数类似于将一个按列xFun(FUN, ..., arg)
传递的参数矩阵传递给一个函数,或者,也许,甚至更普遍。arg
dim(arg)[1] == 2
FUN = function(x, y)
dim(arg)[1] == length(formals(FUN))
数据:
set.seed(42)
M <- matrix(rnorm(30), 10, 3)
解决方案
outer
是你的功能,但你只需要Vectorize
你的corfun
outer(1:3, 1:3, Vectorize(corFun))
# [,1] [,2] [,3]
#[1,] 1.0000000 -0.3749289 0.4400510
#[2,] -0.3749289 1.0000000 -0.1533438
#[3,] 0.4400510 -0.1533438 1.0000000
推荐阅读
- tensorflow - 在我的 MAC M1 Air 上设置深度强化学习环境
- python - check if key is present in every segment of size k in array?
- sql - How to combine multiple SQL Queries without UNION or UNION ALL?
- r - conda hangs indefinitely when installing/activating R
- windows - Trigger Windows Service execution?
- reactjs - 使用 createContext() 和 useContext() 时我做错了什么?
- java - hashset returns only two elements
- angular - 使用 Angular CDN 的多个未捕获的类型错误
- node.js - 为请求添加条件。NodeJs 和 sheetdb-node
- maven - 收到来自服务器的状态码 401:未授权来自远程的 jar