1

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=''))
 }
}
1
  • replace everything with sum(get(paste0("vector_",year))) Commented Feb 13, 2018 at 9:18

1 Answer 1

4

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!

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, this is perfect! :) Thanks.
Is it possible to apply the same method to "input" objects in R Shiny ?
Yes definitely. I recently answered a similar question here. Does that help you?
You can fetch input object by string with input[[x]] where x is your string, is that what you mean? If not, maybe consider opening a new question on Stack Overflow with your desired behavior :)
Well, not really. I've juste asked a new question here where I explain better what I'm trying to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.