Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use apply() with a function that takes more than one input?

Tags:

function

r

apply

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))
like image 849
SavedByJESUS Avatar asked Dec 25 '22 22:12

SavedByJESUS


2 Answers

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 
like image 170
IRTFM Avatar answered Jan 18 '23 23:01

IRTFM


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
like image 29
Metrics Avatar answered Jan 19 '23 00:01

Metrics