[R] new syntax: bash-like pipe operator

From: Robert Sugar <robert.sugar_at_ebi.ac.uk>
Date: Tue, 29 Mar 2011 14:56:17 +0100


Dear R Community,

One thing that always bugged me about R is the abundance of multi-level nested statements, like:

cumsum(ifelse(c(1,diff(v)),1,0))

because:

  1. you have to read them inside out as opposed to left-to-right
  2. in the console you always have to go back and type the parenthesis if you want to nest your statement I kind of like the UNIX pipe operator as a very good abstraction of a data flow and would fancy to have something like this in R: v %|% diff %|% c(1, value) %|% ifelse(value, 1, 0) %|% cumsum so I went ahead and wrote it:

"%|%" <- function(x,y)
{
# Operator similar to the UNIX pipe operator. Allows to set up a chain of functions
# where the result of one function will be the input of the next.
#
# x: any R statement. will be passed to y as a parameter
# y: either a) the name of a single-parameter function or b) a function call, where "value"
# will be replaced with the x parameter

#	

# Example use 1: > c(1,2,3) %|% sum
# results in [1] 6
# Example use 2: > c(1,2,3) %|% rep(value, 10)
# results in [1] 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
        

        thecall<-match.call() #get call         

	#for functions with one parameter call it with x. Example: "c(1,2,3) %|% sum" -> 6
	if(is.name(thecall$y) || is.function(thecall$y)) return (y(x)) 			
	
	#instead of value use x
	value <- eval(thecall$x)
	
	return(eval(thecall$y)) #evaluate

}

would be happy to receive some feedback on

  1. Would you find this useful?
  2. Is there any bugs/features that you'd like to mention?
  3. Should I go ahead and make an R package on that?

Cheers,
Robert

        [[alternative HTML version deleted]]



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue 29 Mar 2011 - 15:35:39 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 29 Mar 2011 - 16:30:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive