user3347232
user3347232

Reputation: 427

Replace for-loop with apply()?

I am trying to optimise my R code and I have started replacing loops that have been implemented “quick and dirty” with functions and so on. I have now arrived at a situation where I believe the apply-function would be handy. I cannot wrap my head around it though.

a <- c(10,20,15,43,76,41,25,46)
c <- c(2,5,8,3,6,1,5,6)                               
myframe <- data.frame(a,c)
newframe <-vector(length=3)
constant <- data.frame(a,c,a,a,a,a,a,a,a,a,a,a,c)

a.function <- function(frame){
  newframe <- frame*22
  return(newframe)}

result <-  matrix(nrow=nrow(myframe),ncol=3)

for(i in 1:nrow(myframe)){
  newframe <- a.function(myframe[i,])
  newframe[ncol(myframe)+1] = i 
  newframe[ncol(myframe)+2] = constant[i,9]
  #more columns added
  newframe <- rbind(result,newframe)
}

I have tried to reduce the loop as far as possible and I hope it can still be understood. Going through the rows of a dataframe should be the prime example for the use of a for function. Still I cannot get it to work. Any ideas?

EDIT: I've added a working example.

Upvotes: 0

Views: 618

Answers (1)

jtanman
jtanman

Reputation: 684

This code overwrites itself. Instead of saving each run through of the loop. You're rewriting newframe every loop through with data from myframe. Basically the only thing your loop does is run the last value of i which is nrow(myframe)

newframe <- a.function(myframe[nrow(myframe),])
newframe[ncol(myframe)+1] = nrow(myframe)
newframe <- rbind(newframe,newframe)

and

result <-  matrix(nrow=nrow(myframe),ncol=3)

is never even used.

Upvotes: 1

Related Questions