Skip to content
Prev 49169 / 63424 Next

Most efficient way to check the length of a variable mentioned in a formula.

Dear R gurus,

I need to know the length of a variable (let's call that X) that is
mentioned in a formula. So obviously I look for the environment from which
the formula is called and then I have two options:

- using eval(parse(text='length(X)'),
                    envir=environment(formula) )

- using length(get('X'),
            envir=environment(formula) )

a bit of benchmarking showed that the first option is about 20 times
slower, to that extent that if I repeat it 10,000 times I save more than
half a second. So speed is not really an issue here.

Personally I'd go for option 2 as that one is easier to read and does the
job nicely, but with these functions I'm always a bit afraid that I'm
overseeing important details or side effects here (possibly memory issues
when working with larger data).

Anybody an idea what the dangers are of these methods, and which one is the
most robust method?

Thank you
Joris