Skip to content

Instantly share code, notes, and snippets.

@EoinTravers
Last active August 17, 2018 11:55
Show Gist options
  • Save EoinTravers/538fb271908342ea6651862a8c928bd8 to your computer and use it in GitHub Desktop.
Save EoinTravers/538fb271908342ea6651862a8c928bd8 to your computer and use it in GitHub Desktop.
dplyr as a CLI. Never use awk again.
#!/usr/bin/env Rscript
# (Don't forget: `chmod +x dplyr`)
# Copyright 2018 Eoin Travers <[email protected]>
#
# This file is free software: you may copy, redistribute and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 2 of the License, or (at your
# option) any later version.
#
# This file is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
suppressMessages(library(optparse))
suppressMessages(library(dplyr))
option_list <- list(
make_option(c("-p", "--pretty"), action="store_true", default=FALSE,
help="Print result tibble, rather than raw csv. [default FALSE]")
)
parser <- OptionParser(
usage = "dplyr [options] data.csv 'data %>% command1() %>% command2()'",
option_list=option_list)
arguments <- parse_args(parser, positional_arguments = 2)
args <- arguments$args
stopifnot(length(args)==2)
inp <- args[[1]]
cmd <- args[[2]]
data <- read.csv(inp) %>% as.tbl
result <- parse(text=cmd) %>% eval()
if(arguments$options$pretty){
print(result)
} else {
txt <- textConnection('csv_result', 'w')
write.csv(result, txt, quote=F, row.names=F)
paste(csv_result, collapse='\n') %>% paste0('\n') %>% cat()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment