2

I am inserting some code into someone else's custom R package and I don't have flexibility to write it how I would like.

I need to be able to sum up many variables following a similar format that I can re-create with formulas.

I am looking for a more efficient way to write this. Efficiency is important because there is a lot of data to process.

Here is sample code showing what I want to do, but it is slow and clunky. I know eval-parse is not the best way to do this, that's why I'm asking for a better way :-)

v1 <- 1 v2 <- 2 v3 <- 3 v4 <- 4 # this for loop works, but it is clunky and slow string <- character() for (i in 1:4) { if (i < 4) string <- c(string, paste0("v",i,"+")) else string <- c(string, paste0("v",i)) } eval(parse(text=string)) 
5
  • 2
    Looks like Reduce("+", mget(paste0("v", 1:4))) Commented Sep 10, 2019 at 18:31
  • Are you looking for this? Commented Sep 10, 2019 at 18:56
  • 3
    1) You don't need a loop to form the string: paste0("v", 1:4, collapse = "+"). 2) An alternative to @akrun's Reduce can be Reduce("+", mget(ls(pattern = "^v\\d+$"))). Commented Sep 10, 2019 at 18:59
  • akrun's answer is perfect, thank you!! Commented Sep 10, 2019 at 19:06
  • 1
    Thanks d.b, I will have to benchmark those methods vs the Reduce solution when I get the chance Commented Sep 10, 2019 at 19:09

2 Answers 2

2

We can use Reduce after getting the object values in a list

Reduce(`+`, mget(paste0("v", 1:4))) 
Sign up to request clarification or add additional context in comments.

Comments

0

Since you talk about formulas, maybe reformulate() can help

reformulate(paste0("v",1:4)) #> ~v1 + v2 + v3 + v4 

You can get your expected output by using the following, though in that case it's less efficient and less intuitive than @akrun's approach :

eval(reformulate(paste0("v",1:4))[[2]]) #> [1] 10 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.