Home > Software engineering >  Are there any codes that work more effectively instead of loop in R?
Are there any codes that work more effectively instead of loop in R?

Time:12-17

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)))
  }
}

CodePudding user response:

You can avoid sapply / for loops if you use c() instead of list() in your x definition:

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

func1(unlist(mget(x)))

# a  b  c  d  e 
# 1  4  9 16 25 

CodePudding user response:

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

CodePudding user response:

You can vectorize func1, then check if appnd1 exists and then check what to do:

tmp <- lapply(x, func1)
tmp <- do.call(rbind, tmp)

if(!exists("append1")){
  appnd1 <- tmp
} else{
  appnd1 <- rbind(appnd1, tmp)
}

CodePudding user response:

A bit convoluted way to sum variables :-) but here is my try

By the way what's inefficient in you loop is the successive rbinding of intermediate results.

# vertically bind computed values
appnd1 <- do.call(rbind,
  # apply func1 on values of listed variables
  lapply(
    # get values of listed variables
    lapply(
      x, 
      get,
      mode="numeric" # otherwise 'c' will return the function 'c()'
    ), 
  func1
  )
)

Got as result

     [,1]
[1,]    1
[2,]    4
[3,]    9
[4,]   16
[5,]   25
  •  Tags:  
  • r
  • Related