datajoel
datajoel

Reputation: 100

What is an alternative to this eval parse code?

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))

Upvotes: 2

Views: 663

Answers (2)

moodymudskipper
moodymudskipper

Reputation: 47300

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

Upvotes: 0

akrun
akrun

Reputation: 886938

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

Reduce(`+`, mget(paste0("v", 1:4)))

Upvotes: 2

Related Questions