jblackt
jblackt

Reputation: 43

R repeating a function

I have a list with not limited count: parameter<-2,1,3,4,5...... And I would like to repeat a function with the parameter:

 MyFunction('2')

 MyFunction('1')

 MyFunction('3')  etc.

Thank you very much for any tips

Upvotes: 3

Views: 144

Answers (1)

Andrew Brēza
Andrew Brēza

Reputation: 8317

Like most things in R, there's more than one way of handling this problem. The tidyverse solution is first, followed by base R.

purrr/map

I don't have detail about your desired output, but the map function from the purrr package will work in the situation you describe. Let's use the function plus_one() to demonstrate.

library(tidyverse) # Loads purrr and other useful functions

plus_one <- function(x) {x + 1} # Define our demo function

parameter <- c(1,2,3,4,5,6,7,8,9)

map(parameter, plus_one)

map returns a list, which isn't always desired. There are specialized versions of map for specific kinds of output. Depending on what you want to do, you map_chr, map_int, etc. In this case, we could use map_dbl to get a vector of the returned values.

map_dbl(parameter, plus_one)

Base R

The apply family of functions from base R could also meet your needs. I prefer using purrr but some people like to stick with built-in functions.

lapply(parameter, plus_one)
sapply(parameter, plus_one)

You end up with the same results.

identical({map(parameter, plus_one)}, {lapply(parameter, plus_one)})
# [1] TRUE

Upvotes: 1

Related Questions