asokol
asokol

Reputation: 129

How to loop local functions?

I made a function in R that I would like to loop. I have gotten the function to work in a single case. I can't get the function to return the vector of number produced by the function.

vec_fun5 <- function(x,y){
  Vec <- c(round(mean(x[[y]],na.rm=T),2),nrow(na.omit(x[,y])),length(which(x[,y]==1)),length(which(x[,y]==2)),length(which(x[,y]==3)),length(which(x[,y]==4)),length(which(x[,y]==5)))
  return(Vec)
}

for(i in 20:24){
  vec_fun5(x,i)
}

I would like to produce a data frame with all of the vectors produced by the loop.

Upvotes: 0

Views: 124

Answers (1)

h3ab74
h3ab74

Reputation: 328

Maybe you can try putting the objects created by the function in a list:

vec_save <- list()

ii <- 1
for(i in 20:24){
 vec_save[[ii]] <- vec_fun5(x,i)
 ii <- ii+1
}

Following this, if you would like to cbind or rbind the vectors of interest to obtain a single dataframe, you can just run:

df <- do.call("cbind", vec_save) #assuming that you want to bind them by column

Upvotes: 1

Related Questions