I've written the following function based on subset()
, which I find handy:
ss <- function (x, subset, ...)
{
r <- eval(substitute(subset), data.frame(.=x), parent.frame())
if (!is.logical(r))
stop("'subset' must be logical")
x[r & !is.na(r)]
}
So, I can write:
ss(myDataFrame$MyVariableName, 500 < . & . < 1500)
instead of
myDataFrame$MyVariableName[ 500 < myDataFrame$MyVariableName
& myDataFrame$MyVariableName < 1500]
This seems like something other people might have developed solutions for, though - including something in core R I might have missed. Anything already out there?
I realize that the solution Ken offers is more general than just selecting items within ranges (since it should work on any logical expression) but this did remind me that Greg Snow has comparison infix operators in his Teaching Demos package:
Thanks for sharing Ken.
You could use:
Yours may require less typing but the code is less generalizable to others if you're sharing code. I have a few time saver functions like that myself but use them sparingly because they may be slowing down your code (extra steps) and requires you to also include that code for that function when ever you share the file with someone else.
Compare writing length. Almost the same length:
Compare time on 1000 replications.
So I guess it depends on if you need speed and/or sharability vs convenience. If it's just for you on a small data set I'd say it's valuable.
EDIT: NEW BENCHMARKING