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))
We can use Reduce
after getting the object values in a list
Reduce(`+`, mget(paste0("v", 1:4)))