Home Apply a function within a loop
Reply: 1

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#
Florian Reply to 2018-02-13 09:33:14Z

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!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.322661 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO