Skip to content

Instantly share code, notes, and snippets.

@mschubert
Last active August 29, 2015 13:56
Show Gist options
  • Save mschubert/9061206 to your computer and use it in GitHub Desktop.
Save mschubert/9061206 to your computer and use it in GitHub Desktop.
A unix-like pipe operator in R to perform CLI operations (or call R functions)
sed = function(x, pattern) {
mynames = names(x)
x = sapply(x, function(i) {
type = class(i)
result = system(paste("echo ", i, " | sed ", pattern, sep=""), intern=TRUE)
class(result) = type
result
})
names(x) = mynames
x
}
'%sed%' = function(x, pattern) {
sed(x, pattern)
}
egrep = function(x, pattern) {
stopifnot(class(pattern) == 'character' || class(pattern) == 'numeric')
type = class(x)
result = list()
for (i in as.list(x)) {
tryCatch({
result = c(result,
system(paste("echo ", i, " | grep ", pattern, sep=""), intern=TRUE))
},
error = function(e) {
NULL
},
warning = function(w) {
NULL
})
}
class(result) = type
result
}
'%grep%' = function(x, pattern) {
egrep(x, pattern)
}
@klmr
Copy link

klmr commented Feb 18, 2014

Here’s my unsolicited code review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment