I have a 10 x 5 data frame and a function that receives 2 inputs a
and b
.
a
is a vector and b
is an integer.
The function fun
calculates the mean of the vector a
and multiplies it by b
and returns the result. In the following code, I try to apply()
this function to every column of x
but it does not seem to work. 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(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.
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. However, if you have two or more than two inputs, you can use these as lists and then use Map
function. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With