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 takes 2 inputs a and b .

a is a vector, and b is an integer.

The fun function calculates the average value of the vector a and multiplies it by b and returns the result. In the following code, I try to apply() use this function for each x column, but it does not work. Help me 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)) 
+4
source share
2 answers

If you want to pass more than one parameter to the "apply" function, where one of them is a column vector and the other is a constant, you can do this in two ways:

 apply(x, 2, fun, b=2) 

OR

 apply(x, 2, function(x) {fun(x, 2)} ) 

Perhaps the apparent-odd behavior of R is that the expression fun(x,2) not a function, while 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 
+6
source

The problem here is simple, since you have a constant value for b. However, if you have two or more than two inputs, you can use them as lists, and then use the 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 
+2
source

Source: https://habr.com/ru/post/1496448/


All Articles