user59419
user59419

Reputation: 993

Applying different function in R in a loop

Assuming I have vector or a list. I would like to apply some functions to this list in a loop for example: to find the mean, standard deviation, median, autocorrelation function and many more. How to pass them as argument or apply them automatically in a loop. For example I mean the following :

iterative_function<- function(data, function_names)
  for (ii in 1:length(function_names)

        A=lapply(data, function_names(ii))

This function should be called like this

iterative_function(X,c(mean,std,... act))

This means applying the function one by one to the element of the list.

Upvotes: 0

Views: 248

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

We can loop over each function and apply it on every element of the list

#Thanks to @itslwg for simplifying the function
iterative_fun <- function(data, fun) {
   lapply(fun, function(x) sapply(data, x))
}

iterative_fun(data, c(sd, sum))
#[[1]]
#    a     b 
#1.581 2.160 

#[[2]]
# a  b 
#15 91 

data

Tried on this data

data <- list(a = 1:5, b = 16:10)

Upvotes: 2

Related Questions