Are there any codes that work more effectively instead of loop in R?

0

Issue

Hi I’m new to R programming,
We know that apply family returns faster results than loops. I tried to explain what I want to do with a simple and small example below. When there is a large data, the run time also increases. For this reason, is there a more effective method instead of loop?

a <- 1; b <- 2; c <- 3; d <- 4; e <- 5

func1 <- function(x) x * x

x <- list('a', 'b', 'c', 'd', 'e')

for (i in x) {
  if (exists("appnd1") == F) {
      appnd1<-func1(get(i))
  } else { 
      appnd1 <- rbind(appnd1, func1(get(i)))
  }
}

Solution

One way to do this quickly is with sapply and an anonymous function:

a <- 1; b <- 2; c <- 3;d <- 4; e <- 5
func1 <- function(x) x * x
x <- list('a', 'b', 'c', 'd', 'e')
sapply(x, function(y) func1(get(y)))
## [1]  1  4  9 16 25

Answered By – Miff

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More