3

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

1
  • 1
    Have a look at lapply, something like: lapply(parameter, MyFunction). Commented Jul 26, 2017 at 17:33

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

How would you do the same thing if MyFuntion took two arguments. One is the parameter one is the name of the df. Something like this? MyFunction(dataframe,'2').

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.