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

Joris Meys jorismeys at gmail.com
Fri Oct 17 20:04:33 CEST 2014

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 Meys
Statistical consultant

Ghent University
Faculty of Bioscience Engineering
Department of Mathematical Modelling, Statistics and Bio-Informatics

tel : +32 9 264 59 87
Joris.Meys at Ugent.be
Disclaimer : http://helpdesk.ugent.be/e-maildisclaimer.php

	[[alternative HTML version deleted]]

More information about the R-devel mailing list