Pages

Labels

R (14) Admin (11) programming (9) Rant (6) personal (5) parallelism (3) spectrum (3) HPC (2) Rcpp (2) SQL (2) amazon (2) code (2) email (2) frequency (2) git (2) plotting (2) postgresql (2) rstudio (2) school (2) DNS (1) Egypt (1) Flying Cars (1) Future (1) Internet (1) LVM (1) Modeling (1) Mubarak (1) Music (1) Obama (1) Politics (1) RAID (1) Reproducible Research (1) Science (1) Teaching (1) animation (1) apache (1) aws (1) cloud (1) ebay shame phone nyt (1) ec2 (1) economics (1) eff (1) encryption (1) example (1) graphing (1) hardware (1) https (1) knitr (1) knoxville xmas08 mobile pic (1) link (1) linux (1) math (1) performance (1) pki (1) plyr (1) security (1) ssh (1) syntax (1) tech audio (1) ubuntu (1) useR (1)

07 June 2013

Symmetric set differences in R

My .Rprofile contains a collection of convenience functions and function abbreviations. These are either functions I use dozens of times a day and prefer not to type in full:
## my abbreviation of head()
h <- function(x, n=10) head(x, n)
## and summary()
ss <- summary
Or problems that I'd rather figure out once, and only once:
## example:
## between( 1:10, 5.5, 6.5 )
between <- function(x, low, high, ineq=F) {
    ## like SQL between, return logical index
    if (ineq) {
        x >= low & x <= high
    } else {
        x > low & x < high
    }
}
One of these "problems" that's been rattling around in my head is the fact that setdiff(x, y) is asymmetric, and has no options to modify this. With some regularity, I want to know if two sets are equal, and if not, what are the differing elements. setequal(x, y) gives me a boolean answer to the first question. It would *seem* that setdiff(x, y) would identify those elements. However, I find the following result rather counter-intuitive:
> setdiff(1:5, 1:6) 
integer(0)
I personally dislike having to type both setdiff(x,y) and setdiff(y,x) to identify the differing elements, as well as remember which is the reference set (here, the second argument, which I find personally counterintuitive). With this in mind, here's a snappy little function that returns the symmetric set difference:
symdiff <- function( x, y) { setdiff( union(x, y), intersect(x, y))}
> symdiff(1:5, 1:6) == symdiff(1:6, 1:5)
[1] TRUE

Tada! A new function for my .Rprofile!

No comments:

Post a Comment