Home Apply a function within a loop

# Apply a function within a loop

Chloe_pa
1#
Chloe_pa Published in 2018-02-13 09:13:06Z
 Let's say we have 4 vectors, each one of them corresponding to values of some indicator in year i (i is between 11 and 14): vector_11 <- c(1,2,3,4) vector_12 <- c(5,6,7,8) vector_13 <- c(9,10,11,12) vector_14 <- c(13,14,15,16)  ... and the following function : myfunction <- function (vect){ res <- sum(vect) return(res) }  I'd like to "select" the vector according to the value of another variable : year. And then, apply myfunction() to the corresponding vector. I've tried to do this with a loop, and the function paste() but the problem is that R reads it as a character argument : year <- 14 for (i in 11:14){ if (year==i){ vect <- myfunction(paste("vector_",i,sep='')) } } 
Florian
2#
 You could use get() to fetch the object from the environment. So this should work: vector_11 <- c(1,2,3,4) vector_12 <- c(5,6,7,8) vector_13 <- c(9,10,11,12) vector_14 <- c(13,14,15,16) myfunction <- function (vect){ res <- sum(vect) return(res) } year <- 14 for (i in 11:14){ if (year==i){ vect <- myfunction(get(paste("vector_",i,sep=''))) } }  However, it may be easier/better practice to just put the vectors in a named list, and subset from that list, e.g.: mylist = list('11' = c(1,2,3,4), '12'= c(5,6,7,8), '13'= c(9,10,11,12), '14'= c(13,14,15,16)) myfunction <- function (vect){ res <- sum(vect) return(res) } year <- 14 for (i in 11:14){ if (year==i){ vect <- myfunction(mylist[[as.character(year)]]) } }  Hope this helps!