Home > Blockchain >  Perform a series of operations on a vector in R without a loop
Perform a series of operations on a vector in R without a loop

Time:11-23

I've got a vector that I want to perform the same operation on multiple times in series, modifying one argument, and I can't figure out a way to do it without a loop.

For example, say I want to take the vector c(1, 2, 3) and I want to perform a series of logs on it. In a loop, I would do this:

foo <- 30:32
for(anum in c(2,3,4)){
  foo <- log(foo, base = anum)
}

A way to do it without a loop would be:

30:32 |>
  log(base = 2) |>
  log(base = 3) |>
  log(base = 4)

What I'm wanting is to have a function that will take 2:4 as an argument and do this. So something like:

30:32 |> serialfunction(log, 2:4)

Does a function like this exist?

Thanks!

CodePudding user response:

There's not really a built-in function that does exactly that. But you can do this with Reduce. For example

Reduce(function(x, y) {log(x, base=y)}, 2:4, init=30:32)
# [1] 0.2669627 0.2713007 0.2754373

You could create serial function with

serialfunction <- function(x, fun, y) {
   Reduce(function(x, y) {fun(x, y)}, y, init=x)
}
30:32 |> serialfunction(log, 2:4)
# [1] 0.2669627 0.2713007 0.2754373
  • Related