Saurabh
Saurabh

Reputation: 1626

Iterating over a vector and calling a function in R

I have a character vector having 5 elements and I want to call a function foo for each of these elements. Here is the example -

foo <- function(printMe)
{
   print(printMe)
}

vec <- c("Hello", "How are you?", "Take Care", "Welcome", "Goodbye")

What should be the best way to call the function foo for each element of the vector?

Upvotes: 0

Views: 97

Answers (2)

Miff
Miff

Reputation: 7941

There's a function Vectorize() in R to do this, so you can just do:

Vectorize(foo)(vec)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388807

If your function is vectorised (like in this example) you can pass the vector directly in the function.

foo(vec)

If your function is not vectorised meaning it can handle only one input at a given time, you can use any of the looping method available.

#1. for loop
for(i in vec) {
  foo(i)
}

#2. sapply/lapply
sapply(vec, foo)
lapply(vec, foo)

#3. purrr::map
purrr::map(vec, foo)

Upvotes: 2

Related Questions