R:将函数应用于以向量元素作为参数的矩阵 [英] R: Apply function to matrix with elements of vector as argument
问题描述
假设我想对矩阵的每一行应用一个函数.该函数的参数之一采用向量.我想将向量的第一个元素应用于第一行,将第二个元素应用于第二行,依此类推.
Suppose I want to apply a function to each row of a matrix. One of the function's arguments takes a vector. I would like to apply the first element of the vector to the first row, the second element to the second row, etc.
例如:
set.seed(123)
df<-matrix(runif(100), ncol=10)
var2 <- c(1:10)
MYFUNC <- function(x, Var=NA){
sum(x)/Var
}
我试过了:
apply(df, 1, function(x) MYFUNC(x, Var=var2))
但是这给了我一个 10x10 的矩阵,其中的函数应用于每一行 &Var 组合,而我只对对角线元素感兴趣.我还研究了 mapply
函数,但我不确定如何在这种情况下应用它.
But that gives me a 10x10 matrix with the function applied to each row & Var combination, whereas I'm only interested in the diagonal elements. I also looked into the mapply
function, but I'm not sure how to apply it in this case.
任何帮助将不胜感激.
推荐答案
Mapply
绝对是一种可能.这应该有效:
Mapply
is definitely a possibility. This should work:
mapply(MYFUNC, x = as.data.frame(t(df)), Var = var2)
#V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
#5.0795111 2.8693537 1.8285747 1.3640238 0.8300597 0.6280441 0.7706310 0.6720132 0.5719003 0.4259674
我认为您遇到的问题是 mapply
接受向量或列表.在 R 中,矩阵不是列表,但 data.frame
是.您需要做的就是转置您的矩阵并转换为 data.frame
然后 mapply
应该可以工作.data.frame
中的每一列都是列表中的一个元素,这就是我们必须对其进行转置的原因(以便每个 row
将映射到向量中的每个元素).
The issue I think you were running into is that mapply
takes either vectors or lists. In R matrices aren't lists, but data.frame
s are. All you need to do is transpose your matrix and convert to a data.frame
and then mapply
should work. Each column in a data.frame
is an element in the list which is why we have to transpose it (so that each row
will be mapped to each element in the vector).
这篇关于R:将函数应用于以向量元素作为参数的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!