Skip to content

Instantly share code, notes, and snippets.

@alekrutkowski
Last active November 17, 2022 16:31
Show Gist options
  • Save alekrutkowski/718be72c5c0c8c24c69af3b1d18f1cf7 to your computer and use it in GitHub Desktop.
Save alekrutkowski/718be72c5c0c8c24c69af3b1d18f1cf7 to your computer and use it in GitHub Desktop.
Functions and active bindings for rapid interactive work in R
options(width=200)
if (interactive()) {
message('================================================================================')
ab <- function(sym_as_str, fun)
makeActiveBinding(sym_as_str, fun, .GlobalEnv)
library(magrittr)
message('- Imported package `magrittr`')
library(data.table)
message('- Imported package `data.table`')
library(openxlsx2)
message('- Imported package `openxlsx2`')
library(eurodata)
message('- Imported package `eurodata`')
ct <- . %>% cat(sep='\n')
message('- Use ct(my_charvec) instead of cat(.,sep="\\n")')
x <- viewxl::view_in_xl
message('- Use x(my_df) to view a data.frame in Excel.')
md <- . %>%
knitr::kable() %>%
capture.output() %>%
paste('# ',.) %>%
.[-(1:2)] %T>%
writeClipboard() %>%
ct()
message('- Use md(my_df) to print a data.frame as a markdown table and copy it to clipboard.')
tsv <- . %>%
write.table("clipboard", sep="\t", row.names=FALSE)
message('- Use tsv(my_df) to "paste" a data.frame to clipboard as tsv.')
ab('v', function() { # v = like Ctrl+V
val <-
readr::read_delim(readr::clipboard()) %>% # more robust to strange chars than fread or read_table
as.data.frame() %>% # to remove unneeded attributes
as.data.table()
msg <-
'Pasted from clipboard'
message('### ',msg,':')
str(val)
View(val,msg)
val
})
message('- Use my_dt <- v (active binding) to "paste" a data.table from clipboard.')
ab('pp', function() { # pp = pretty path
x <- readClipboard()
x %>%
gsub('\\','/',.,fixed=TRUE) %T>%
cat(file='clipboard',.) %>% # not writeClipboard() to avoid adding \n at the end
message(x,"\n\t|\n\tV\n",.)})
message('- Use pp (active binding) to modify the clipboard in place replacing \\ with /')
ab('lv', function() { # lv = lines -> vector
x <- readClipboard()
x %>%
paste(collapse=',\n') %>%
paste0('c(\n',.,'\n)') %T>%
cat(file='clipboard',.) %>% # not writeClipboard() to avoid adding \n at the end
message('Clipboard now contains:\n',.)})
message('- Use lv (active binding) to turn lines in clipboard into an R vector')
ab('vv', function() # even faster than `v` above
assign('xxx',
v,
envir=.GlobalEnv))
message('- Use vv (active binding) instead of xxx <- v to "paste" a data.table from clipboard.')
readAllSheets <- function(xlsx_file_name, drop_empty_sheets=TRUE, ...)
xlsx_file_name %>%
read_sheet_names() %>%
sapply(function(x)
try(suppressWarnings(read_xlsx(xlsx_file_name,x, ...)), silent=TRUE) %>%
`if`(inherits(.,'try-error') &&
attr(.,'condition')$message=='dims are inf:-inf', # empty worksheet
`if`(!drop_empty_sheets, data.frame())
,.),
simplify=FALSE) %>%
.[!sapply(.,is.null)]
ab('dd', function() { # dd = dynamic data
x <-
readClipboard() %>%
gsub('\\','/',.,fixed=TRUE) %>%
gsub('"',"",.,fixed=TRUE)
file_name <-
basename(x) %>%
paste0("`",.,"`")
cmd_line <-
`if`(tools::file_ext(x)=='xlsx',
paste0('readAllSheets("',x,'") %>% lapply(. %>% as.data.frame() %>% as.data.table())'),
paste0('readr::read_delim("',x,'") %>% as.data.frame() %>% as.data.table()')) %>%
paste(file_name,'<-',.)
cat(cmd_line,'\n\n')
eval(parse(text=cmd_line),
envir=.GlobalEnv)
cmd <-
paste0('str(',file_name,'); View(',file_name,')')
cat(cmd,'\n\n')
eval(parse(text=cmd),
envir=.GlobalEnv)
})
message('- Use dd (active binding) instead of\n',
' my_file_name <-\n\trespective_import_func("/path/to/my_file_name")\n',
' to import as a data.table from the file path in clipboard\n',
' (csv, tsv, or xlsx are supported).')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment