我经常需要将函数应用于数据框/矩阵中的每对列,并以矩阵形式返回结果.现在我总是写一个循环来做这件事.例如,要创建一个包含相关p值的矩阵,我写道:
df <- data.frame(x=rnorm(100),y=rnorm(100),z=rnorm(100))
n <- ncol(df)
foo <- matrix(0,n,n)
for ( i in 1:n)
{
for (j in i:n)
{
foo[i,j] <- cor.test(df[,i],df[,j])$p.value
}
}
foo[lower.tri(foo)] <- t(foo)[lower.tri(foo)]
foo
[,1] [,2] [,3]
[1,] 0.0000000 0.7215071 0.5651266
[2,] 0.7215071 0.0000000 0.9019746
[3,] 0.5651266 0.9019746 0.0000000
Run Code Online (Sandbox Code Playgroud)
哪个有效,但对于非常大的矩阵来说非常慢.我可以在R中为此编写一个函数(通过假设如上所述的对称结果,不会因为切割时间减半而烦恼):
Papply <- function(x,fun)
{
n <- ncol(x)
foo <- matrix(0,n,n)
for ( i in 1:n)
{
for (j in 1:n)
{
foo[i,j] <- fun(x[,i],x[,j])
}
}
return(foo)
}
Run Code Online (Sandbox Code Playgroud)
或者是Rcpp的函数:
library("Rcpp")
library("inline")
src <-
' …
Run Code Online (Sandbox Code Playgroud) 我想拿出一个变种mapply
(称它为xapply
现在),它结合了功能(在某种程度上)的expand.grid
和mapply
.也就是说,对于一个功能FUN
和参数列表L1
,L2
,L3
,...的长度未知,但应该产生长度的列表n1*n2*n3
(其中,ni
是列表的长度i
),这是施加的结果FUN
到的元素的所有组合名单.
如果expand.grid
用于生成列表而不是数据框列表,则可以使用它,但我记得列表可能是不一定适合数据框的事物列表.
如果有三个要扩展的列表,这个功能可以正常工作,但我很好奇一个更通用的解决方案.(FLATTEN
未使用,但我可以想象这FLATTEN=FALSE
将生成嵌套列表而不是单个列表...)
xapply3 <- function(FUN,L1,L2,L3,FLATTEN=TRUE,MoreArgs=NULL) {
retlist <- list()
count <- 1
for (i in seq_along(L1)) {
for (j in seq_along(L2)) {
for (k in seq_along(L3)) {
retlist[[count]] <- do.call(FUN,c(list(L1[[i]],L2[[j]],L3[[k]]),MoreArgs))
count <- count+1
}
}
}
retlist
}
Run Code Online (Sandbox Code Playgroud)
编辑:忘了返回结果.有人可能通过combn
在那里制作一份指数清单来解决这个问题......
给定每个维度的p
向量,计算其张量/外部/ Kruskal产品的最佳方法是什么(带有条目的-array X ?循环是微不足道的,但是很愚蠢.使用重复调用可以正常工作,但似乎不是最佳解决方案(显然,随着p增加,速度会变慢).有更好的方法吗?x1,x2,...,xp
d
p
X[i1,i2,..ip] = x1[i1]x2[i2]...xp[ip])
outer
编辑:
我目前最好的是
array(apply(expand.grid(x1, x2, x3), 1, prod), dim=rep(d, 3))
Run Code Online (Sandbox Code Playgroud)
至少"感觉更好"......
编辑2:回应@Dwin,这是一个完整的例子
d=3
x1 = 1:d
x2 = 1:d+3
x3 = 1:d+6
array(apply(expand.grid(x1, x2, x3), 1, prod), dim=rep(d, 3))
, , 1
[,1] [,2] [,3]
[1,] 28 35 42
[2,] 56 70 84
[3,] 84 105 126
, , 2
[,1] [,2] [,3]
[1,] 32 40 48
[2,] 64 80 96
[3,] 96 120 144
, …
Run Code Online (Sandbox Code Playgroud) 考虑矩阵d
和r
with dim(d) = J x D
和dim(r) = J x R
.让fun(a,b)成为一个函数,它接受两个相同长度的向量并返回一些数字.
我想把列的d
和列r
分别作为我感兴趣的单位,并适用outer
于它们.
下面的代码创建的列的列表来完成这个d
和r
,然后同时使用outer
和sapply
:
d.cols <- split(d, col(d))
r.cols <- split(r, col(r))
outer(d.cols, r.cols,
function(x,y) {
sapply(seq_along(x),
function(i) {
Fun(x[[i]], y[[i]]) })} )
Run Code Online (Sandbox Code Playgroud)
代码做我想要的并且相对有效,但是笨拙且不清楚.有没有更好的方法来实现我想要达到的目标?