r - Replace for-loop with apply()? -



r - Replace for-loop with apply()? -

i trying optimise r code , have started replacing loops have been implemented “quick , dirty” functions , on. have arrived @ situation believe apply-function handy. cannot wrap head around 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] = newframe[ncol(myframe)+2] = constant[i,9] #more columns added newframe <- rbind(result,newframe) }

i have tried cut down loop far possible , hope can still understood. going through rows of dataframe should prime illustration utilize of function. still cannot work. ideas?

edit: i've added working example.

this code overwrites itself. instead of saving each run through of loop. you're rewriting newframe every loop through info myframe. thing loop run lastly value of 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 used.

r loops apply

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -