[英]How to use apply() with a function that takes more than one input?
I have a 10 x 5 data frame and a function that receives 2 inputs a
and b
. 我有一个10 x 5数据帧和一个接收2个输入
a
和b
的函数。
a
is a vector and b
is an integer. a
是向量, b
是整数。
The function fun
calculates the mean of the vector a
and multiplies it by b
and returns the result. 函数
fun
计算向量a
的平均值并将其乘以b
并返回结果。 In the following code, I try to apply()
this function to every column of x
but it does not seem to work. 在下面的代码中,我尝试
apply()
此函数应用于x
每一列,但它似乎不起作用。 Help, please! 请帮助!
x = data.frame(rnorm(10), rnorm(10), rnorm(10), rnorm(10), rnorm(10))
fun = function(a, b)
{
c = mean(a) * b
return(c)
}
apply(x, 2, fun(x,2))
If you want to pass more than one parameter to an "apply"-ied function where one of them is the column vector and the other one is a constant, you can do it in two ways; 如果要将多个参数传递给“apply”-ied函数,其中一个是列向量而另一个是常量,则可以通过两种方式完成:
apply(x, 2, fun, b=2)
OR: 要么:
apply(x, 2, function(x) {fun(x, 2)} )
The possibly seen-as-odd behavior of R is that the expression fun(x,2)
is not a function whereas function(x) {fun(x, 2)}
is. R的可能被看作奇怪的行为是表达
fun(x,2)
不是函数而function(x) {fun(x, 2)}
是。
apply(x, 2, fun, b=2)
#------------------
rnorm.10. rnorm.10..1 rnorm.10..2 rnorm.10..3 rnorm.10..4
-0.06806881 0.32749640 -0.14400234 -0.41493410 -0.02669955
Here the problem is simple since you have constant value for b. 这里问题很简单,因为你有b的常数值。 However, if you have two or more than two inputs, you can use these as lists and then use
Map
function. 但是,如果您有两个或两个以上的输入,则可以将它们用作列表,然后使用
Map
功能。 For your example: 对于你的例子:
set.seed(1)
mydata<-data.frame(rnorm(10), rnorm(10), rnorm(10), rnorm(10), rnorm(10))
a<-as.list(names(mydata))
b<-as.list(rep(2,5)) # you can keep b<-2 it doesn't change the results since b is constant
myout<-Map(function(x,y) y*mean(mydata[,x]),a,b)
>myout
[[1]]
[1] 0.2644056
[[2]]
[1] 0.4976899
[[3]]
[1] -0.2673465
[[4]]
[1] 0.2414604
[[5]]
[1] 0.2682734
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.