core_commons.R 17 KB
Newer Older
Holger Brandl's avatar
Holger Brandl committed
1 2 3 4
########################################################################################################################
## set a default cran r mirror  and customize environment

#cat(".Rprofile: Setting Goettingen repository\n")
Holger Brandl's avatar
Holger Brandl committed
5 6
#todo consider to use chooseCRANmirror(graphics=FALSE, ind=10) instead

Holger Brandl's avatar
Holger Brandl committed
7 8 9 10 11 12 13 14 15 16 17 18
r = getOption("repos") # hard code the UK repo for CRAN

r["CRAN"] = "http://ftp5.gwdg.de/pub/misc/cran/"
options(repos = r)
rm(r)


## user browser for help
options(help_type="html")

## plot more characters per line
options(width=150)

19 20 21
## adjust dplyr printing settings
## http://stackoverflow.com/questions/22471256/overriding-variables-not-shown-in-dplyr-to-display-all-columns-from-df
## http://stackoverflow.com/questions/29396111/dplyrtbl-df-fill-whole-screen
22
# options(dplyr.print_min = 20) ## num rows
23
options(dplyr.width = 130) ## width
24
#options(dplyr.width = 250); options(width=250) ## width
25

Holger Brandl's avatar
Holger Brandl committed
26 27 28
# for sqldf to avoid the use of tckl
options(gsubfn.engine = "R")

Holger Brandl's avatar
Holger Brandl committed
29

Holger Brandl's avatar
Holger Brandl committed
30
########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
31
## automatic package installation
Holger Brandl's avatar
Holger Brandl committed
32

Holger Brandl's avatar
Holger Brandl committed
33

34
## externalized installer to also allow for installation without loading
35
install_package <- function(x){
36 37 38 39 40 41 42 43 44 45 46 47 48 49
    if(!isTRUE(x %in% .packages(all.available=TRUE)) && any(available.packages()[,1]==x)) {
        # update.packages(ask=F) # update dependencies, if any.
        eval(parse(text=paste("install.packages('", x, "')", sep="")))
    }

    ## if it's still missing check if it's on bioconductor
    if(!isTRUE(x %in% .packages(all.available=TRUE))) {
        bcPackages <- as.vector(read.dcf(url("https://bioconductor.org/packages/3.3/bioc/src/contrib/PACKAGES"), "Package"))

        if(any(bcPackages==x)){
            source("http://bioconductor.org/biocLite.R")
            eval(parse(text=paste("biocLite('", x, "', ask=FALSE)", sep="")))
        }
    }
50 51
}

Holger Brandl's avatar
Holger Brandl committed
52 53 54
load_pack <-  function(x, warn_conflicts=T){
    x <- as.character(substitute(x));

55
   install_package(x)
Holger Brandl's avatar
Holger Brandl committed
56

57
    ## load it using a library function so that load_pack errors if package is still not ins
Holger Brandl's avatar
Holger Brandl committed
58
    eval(parse(text=paste("base::library(", x, ",  quietly=T, warn.conflicts=", warn_conflicts, ")", sep="")))
Holger Brandl's avatar
Holger Brandl committed
59 60
}

61

62 63 64 65 66 67
check_version = function(pkg_name, min_version) {
    cur_version = packageVersion(pkg_name)
    if(cur_version < min_version) stop(sprintf("Package %s needs a newer version,
               found %s, need at least %s", pkg_name, cur_version, min_version))
}
#check_version("dplyr", "0.4-1")
Holger Brandl's avatar
Holger Brandl committed
68

Holger Brandl's avatar
Holger Brandl committed
69
########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
70
## load core packages
Holger Brandl's avatar
Holger Brandl committed
71

Holger Brandl's avatar
Holger Brandl committed
72 73
#load_pack(plyr)
#load_pack(reshape2)
74
#load_pack(reshape2, quietly=T, warn_conflicts=F)
Holger Brandl's avatar
Holger Brandl committed
75

Holger Brandl's avatar
Holger Brandl committed
76
## load on purpose after plyr
Holger Brandl's avatar
Holger Brandl committed
77
load_pack(purrr)
78 79 80
load_pack(dplyr, warn_conflicts=F)
load_pack(magrittr, warn_conflicts=F)
load_pack(tidyr, warn_conflicts=F)
Holger Brandl's avatar
Holger Brandl committed
81 82
load_pack(stringr)
load_pack(readr)
Holger Brandl's avatar
Holger Brandl committed
83
load_pack(forcats)
Holger Brandl's avatar
Holger Brandl committed
84
load_pack(readxl) ## supress differring build number
85

Holger Brandl's avatar
Holger Brandl committed
86
## needed for caching
87
load_pack(digest)
Holger Brandl's avatar
Holger Brandl committed
88 89 90

#suppressWarnings(load_pack(readxl)) ## supress differring build number

91
#load_pack(readxl) ## supress differring build number
92 93 94


## common plotting requirements since they are omnipresent
95 96 97
load_pack(ggplot2)
load_pack(scales, warn_conflicts=F)
load_pack(grid)
98

Holger Brandl's avatar
Holger Brandl committed
99
## for table exploration without using Rstudio
100
load_pack(DT)
Holger Brandl's avatar
Holger Brandl committed
101

Holger Brandl's avatar
Holger Brandl committed
102 103

## moved into datatable_commons because replaced almost everywhere with dplyr
104
#load_pack(data.table)
Holger Brandl's avatar
Holger Brandl committed
105 106 107 108



########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
109
#### Convenience aliases
Holger Brandl's avatar
Holger Brandl committed
110 111


Holger Brandl's avatar
Holger Brandl committed
112
echo <- function(...) cat(paste(...), fill=T)
Holger Brandl's avatar
Holger Brandl committed
113 114 115 116

ac <- function(...) as.character(...)

# string concatenation without space gaps (could/should use paste0 instead)
Holger Brandl's avatar
Holger Brandl committed
117 118
## Deprecated: use paste0 instead
#concat <- function(...) paste(..., sep="")
Holger Brandl's avatar
Holger Brandl committed
119 120 121 122 123

unlen <- function(x) length(unique(x))

pp <- function(dat) page(dat, method = "print")

Holger Brandl's avatar
Holger Brandl committed
124 125
# TODO .Deprecated and .Defunct (see http://ropensci.org/blog/technotes/2017/01/05/package-evolution)

Holger Brandl's avatar
Holger Brandl committed
126 127
as.df <- function(dt){ warning("DEPRECATED: use as_df instead of as.df"); as.data.frame(dt) }
as_df <- function(dt) as.data.frame(dt)
Holger Brandl's avatar
Holger Brandl committed
128

Holger Brandl's avatar
Holger Brandl committed
129

Holger Brandl's avatar
Holger Brandl committed
130 131 132 133 134
install_package("tibble")

## restore pre-tibble-v1.2 naming to creating data-frame in place
frame_data = function(...) tibble::tribble(...)

135

136
add_rownames = function(...){ warning("DEPRECATED: Use tibble::rownames_to_column directly"); tibble::rownames_to_column(...) }
137

Holger Brandl's avatar
Holger Brandl committed
138 139 140 141 142 143 144 145 146 147 148 149 150

## redefine dply::splat to allow for more streamlined rowwise df-processing
## see https://groups.google.com/forum/?utm_source=digest&utm_medium=email#!topic/manipulatr/E6WOcHlRJcw
#splat = function (flat) {
#    function(args, ...) {
#        do.call(flat, c(args, list(...)))
#    }
#}
## for now simply import just splat from plyr namespace
install_package("plyr")
splat = plyr::splat


Holger Brandl's avatar
Holger Brandl committed
151 152 153 154 155 156 157 158 159 160
########################################################################################################################
#### data.frame manipulation


shuffle <- function(df) df[sample(nrow(df)),]

first <- function(x, n=1) head(x,n)



Holger Brandl's avatar
Holger Brandl committed
161 162 163 164 165 166 167 168
vec2df <- function(namedVec){
    warning("DEPRECATED use vec_as_df instead of vec2df")
    namedVec %>% {data.frame(name=names(.), value=., row.names=NULL)}
}

vec_as_df <- function(namedVec, row_name="name", value_name="value"){
    data_frame(name=names(namedVec), value=namedVec) %>% set_names(row_name, value_name)
}
Holger Brandl's avatar
Holger Brandl committed
169

Holger Brandl's avatar
Holger Brandl committed
170 171

rownames2column <- function(df, colname){
172 173
    warning("DEPRECATED Use dplyr::add_rownames directly")
    add_rownames(df, var=colname)
Holger Brandl's avatar
Holger Brandl committed
174 175 176 177
}


column2rownames<- function(df, colname){
178
    #browser()
Holger Brandl's avatar
Holger Brandl committed
179
    ## force into df to avoid dplyr problems
Holger Brandl's avatar
Holger Brandl committed
180
    df <- as_df(df)
Holger Brandl's avatar
Holger Brandl committed
181

Holger Brandl's avatar
Holger Brandl committed
182 183 184 185 186
    rownames(df) <- ac(df[,colname])
    df[colname] <- NULL
    return(df)
}

Holger Brandl's avatar
Holger Brandl committed
187 188
## pushing some columns to the end of a data.frame
## TBD how to make this possible without quoting column names?
Holger Brandl's avatar
Holger Brandl committed
189 190 191 192 193
push_right <- function(df, pushColNames){
    df[,c(setdiff(names(df),pushColNames), pushColNames)]
}


Holger Brandl's avatar
Holger Brandl committed
194
## pushing some columns to the beginning of a data.frame
Holger Brandl's avatar
Holger Brandl committed
195 196 197 198 199
push_left <- function(df, pushColNames){
    df[,c(pushColNames, setdiff(names(df),pushColNames))]
}


Holger Brandl's avatar
Holger Brandl committed
200
#http://astrostatistics.psu.edu/datasets/R/html/base/html/formals.html
201 202 203 204 205 206 207 208 209 210 211 212 213 214
## disabled because purrr::set_names does the same and even has the same name
# set_names <- function(df, ...){
#     #browser()
#     newnames <- as.character(unlist(list(...)))
#
#     ## automatically convert matrices to data.frames (otherwise the names set would fail
#     if(is.matrix(df)) df %<>% as.data.frame()
#
#     names(df) <- newnames;
#     return(df)
# }
# iris %>% purrr::set_names(paste(names(iris), "__")) %>% glimpse
# iris %>% set_names(paste(names(iris), "__")) %>% glimpse
#
Holger Brandl's avatar
Holger Brandl committed
215 216
#iris %>% set_names(c("setosa", "hallo")) %>% head
#iris %>% set_names("setosa", "hallo") %>% head
Holger Brandl's avatar
Holger Brandl committed
217 218


219 220
rify_names  <- function(df){
    warning("DEPRECATED: use pretty_columns instead");
Holger Brandl's avatar
Holger Brandl committed
221
    names(df) <- names(df) %>% str_replace_all(c(" "="_", "-"="_", "/"="_"));
222 223 224
    df
}

225
pretty_columns = function(df){
226
    names(df) <- names(df) %>%
227
        str_replace_all("[#=.,()/*: -]+", "_") %>%
228 229 230
        str_replace(fixed("["), "") %>%
        str_replace(fixed("]"), "") %>%
        ## remove leading and tailing underscores
231 232
        str_replace("[_]+$", "") %>%
        str_replace("^[_]+", "") %>%
233
        ## remove unicode characters
234 235 236 237 238
        iconv(to = 'ASCII', sub = '') %>% ## http://stackoverflow.com/questions/24807147/removing-unicode-symbols-from-column-names
        tolower %>%
        ## make duplicates unqiue
        make.unique(sep = "_")

239 240
    df
}
Holger Brandl's avatar
Holger Brandl committed
241

242 243
# http://stackoverflow.com/questions/23188900/view-entire-dataframe-when-wrapped-in-tbl-df
print_all <- function(df) df %>% tbl_df %>% print(n = nrow(.))
Holger Brandl's avatar
Holger Brandl committed
244

Holger Brandl's avatar
Holger Brandl committed
245 246
head_html <- function(df, n=5) head(df, n) %>% knitr::kable(format="html") %>% print()

Holger Brandl's avatar
Holger Brandl committed
247 248
print_head <- function(df, desc=NULL){
    print(head(df))
Holger Brandl's avatar
Holger Brandl committed
249
    print(nrow(df))
Holger Brandl's avatar
Holger Brandl committed
250 251 252 253 254
    return(df)
}


fac2char <- function(mydata, convert=names(mydata)[sapply(mydata, is.factor)]){
Holger Brandl's avatar
Holger Brandl committed
255 256 257
    if(length(convert)==0){
        return(mydata)
    }
Holger Brandl's avatar
Holger Brandl committed
258 259 260 261 262 263 264 265 266 267 268 269 270

    inputColOrder <- names(mydata)

    convertData <- subset(mydata, select= names(mydata)%in%convert)
    convertData <- as.data.frame(lapply(convertData, as.character), stringsAsFactors = FALSE)

    keepData <-  subset(mydata, select=!(names(mydata)%in%convert))
    newdata <- cbind(convertData, keepData)
    newdata <- newdata[,inputColOrder]

    return(newdata)
}

Holger Brandl's avatar
Holger Brandl committed
271 272 273 274
## convenience method to sort factor levels with decreasing frequencies
fct_revfreq = function(x) fct_infreq(x) %>% fct_rev


Holger Brandl's avatar
Holger Brandl committed
275
## replace R within pipe change just use ... %>% do(replaceNA(0)) %>% ...
Holger Brandl's avatar
Holger Brandl committed
276
replaceNA <- function(x, withValue) { x[is.na(x)] <- withValue; x }
Holger Brandl's avatar
Holger Brandl committed
277

Holger Brandl's avatar
Holger Brandl committed
278

Holger Brandl's avatar
Holger Brandl committed
279

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297

## see http://stackoverflow.com/questions/17288222/r-find-value-in-multiple-data-frame-columns/40586572#40586572
## case-insenstive search all columns of a data-frame with a fixed search term
search_df = function(df, search_term){
    apply(df, 1, function(r){
        any(str_detect(as.character(r), fixed(search_term, ignore_case=T)))
    }) %>% subset(df, .)
}


## filter a data-frame for those rows where at least one column is matching the given expression (that must evaluate to a boolean vector for each row).
match_df = function(df, search_expr){
    filter_fun = eval(substitute(function(x){search_expr}))

    apply(df, 1, function(r) any(filter_fun(r))) %>% subset(df, .)
}


Holger Brandl's avatar
Holger Brandl committed
298
## todo still needed since there's if_else in dplyr now
Holger Brandl's avatar
Holger Brandl committed
299
safe_ifelse <- function(cond, yes, no) {
300
    warning("DEPRECATED Use dplyr::if_else instead")
Holger Brandl's avatar
Holger Brandl committed
301

Holger Brandl's avatar
Holger Brandl committed
302 303 304 305 306 307
#browser()
    isfacOrChar <- function(x) class(x)  %in% c("factor", "character")

    if (isfacOrChar(yes) | isfacOrChar(no)) {
        yes <- ac(yes)
        no <- ac(no)
308
    }
Holger Brandl's avatar
Holger Brandl committed
309 310

    ifelse(cond,yes,no)
Holger Brandl's avatar
Holger Brandl committed
311 312
}

Holger Brandl's avatar
Holger Brandl committed
313

Holger Brandl's avatar
Holger Brandl committed
314
## for na instead use mutate_each with:
Holger Brandl's avatar
Holger Brandl committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
#empty_as_na <- function(x) safe_ifelse(x=="", NA, x)
#empty_as_na <- function(x) ifelse(class(x)  %in% c("factor", "character") & x=="", NA, x)
empty_as_na <- function(x){
    if("factor" %in% class(x)) x <- as.character(x) ## since ifelse wont work with factors
    ifelse(as.character(x)!="", x, NA)
}

#if(F){ ## DEBUG of empty_as_na
#cond <- allJobs %>% head %$% submit_time %>% c("")
#empty_as_na( cond)
#cond <- allJobs %>% head %$% resubmission_of
#empty_as_na( cond)
#
#empty_as_na( c(1, 2, NA))
#empty_as_na( c("sdf", "sdf2", NA))
#empty_as_na( c("sdf", "sdf2", ""))
#
#myFac <- as.factor(c("sdf", "sdf2", NA))
#empty_as_na( myFac)
#ifelse(as.character(myFac)!="", myFac, NA)
#
#empty_as_na( c("sdf", "sdf2", ""))
#
#iris[1,1] <- ""
#apply(iris, 2, function(x) gsub("^$|^ $", NA, x))
#}


Holger Brandl's avatar
Holger Brandl committed
343 344 345
## see http://stackoverflow.com/questions/24172111/change-the-blank-cells-to-na/33952598#33952598


Holger Brandl's avatar
Holger Brandl committed
346 347 348 349 350 351
## apply dplyr::filter to df but use filter criterions for cross-tabulation beforehand
filter_count <- function(df, ...){
    print(count(df, ...))
    filter(df, ...)
}

Holger Brandl's avatar
Holger Brandl committed
352
# Example: publications %>% count(journal) %>% as("num_pubs")
Holger Brandl's avatar
Holger Brandl committed
353 354 355 356 357
# as = function(df, name){
#     warning("DEPRECATED use 'as_var' instead of 'as'")
#     names(df)[length(names(df))] = name
#     df
# }
358

359
n_as = function(df, name){
Holger Brandl's avatar
Holger Brandl committed
360 361 362 363
    names(df)[length(names(df))] = name
    df
}

Holger Brandl's avatar
Holger Brandl committed
364 365 366 367 368 369 370 371 372 373
#count_occ = function(df, ...) count(df, ...) %>% n_as("num_occ")

dcount= function(df, ...) count(df, ...) %>% n_as("num_occ") %>% count(num_occ)

count_as= function(df, n_name, ...) count(df, ...) %>% n_as(n_name)
#iris %>% count_as("num_occ", Species)
#iris %>% dcross_tab(Species)



Holger Brandl's avatar
Holger Brandl committed
374

Holger Brandl's avatar
Holger Brandl committed
375 376
distinct_all = function (x, ...) distinct(x, ..., .keep_all=T)

Holger Brandl's avatar
Holger Brandl committed
377 378 379 380 381 382
#' Return <code>true</code> if the data.frame is distinct with respect to the provided unqoted variabled names/expressions
is_distinct = function(x, ...){
    distinct(x) %>% nrow == nrow(x)
}


Holger Brandl's avatar
Holger Brandl committed
383 384 385 386
## fetch a column of a matrix in a magrittr pipe. Useful along with str_*
get_col = function(data, col_index) data[, col_index] ## also could use magrittr::extract here


Holger Brandl's avatar
Holger Brandl committed
387 388 389 390
## convience method to extract a column, defaults to _ as separator and the first column
extract_col = function(x, col_index=1, sep="_", num_cols=10){ str_split_fixed(x, sep, num_cols)[,col_index] }


Holger Brandl's avatar
Holger Brandl committed
391

392 393 394 395 396 397 398
reload_dplyr <- function(){
    unloadNamespace('tidyr')
    unloadNamespace('dplyr')
    require(tidyr);require(dplyr)
}


399
## from http://stackoverflow.com/questions/7505547/detach-all-packages-while-working-in-r
400
unload_packages <- function() {
401 402 403 404 405
    basic.packages <- c("package:stats","package:graphics","package:grDevices","package:utils","package:datasets","package:methods","package:base")
    package.list <- search()[ifelse(unlist(gregexpr("package:",search()))==1,TRUE,FALSE)]
    package.list <- setdiff(package.list,basic.packages)
    if (length(package.list)>0)  for (package in package.list) detach(package, character.only=TRUE)
}
Holger Brandl's avatar
Holger Brandl committed
406 407


Holger Brandl's avatar
Holger Brandl committed
408 409 410 411
## workaround for biomart
## Deprecated: load dplyr after biomart to avoid this problem
#dselect <- function(...) dplyr::select(...)

Holger Brandl's avatar
Holger Brandl committed
412

Holger Brandl's avatar
Holger Brandl committed
413
########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
414
#### Result Caching for long running tasks
Holger Brandl's avatar
Holger Brandl committed
415

Holger Brandl's avatar
Holger Brandl committed
416 417
## related: http://cran.r-project.org/web/packages/R.cache/R.cache.pdf

418
cache_it <- function(expr, filePrefix="cache"){
419
    cacheFile <- paste0(filePrefix, "_", substr(digest::digest(deparse(expr)), 1,6)) %>% paste0(".", ., ".RData")
Holger Brandl's avatar
Holger Brandl committed
420

Holger Brandl's avatar
Holger Brandl committed
421 422 423 424 425 426 427 428 429 430 431
    if(file.exists(cacheFile)){
        local(get(load(cacheFile)))
    } else {
        result <- eval(expr)
        save(result, file=cacheFile)
        result
    }
}

## Examples
#mydata <- quote(iris %>% filter(Species=="setosa")) %>% cache_it("tt")
Holger Brandl's avatar
Holger Brandl committed
432 433
#mydata <- quote(iris %>% filter(Species=="setosa")) %>% cache_it()
#mydata <- quote( { print("evaluate expr"); iris %>% filter(Species=="setosa") } ) %>% cache_it()
Holger Brandl's avatar
Holger Brandl committed
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451

########################################################################################################################
#### File System

is.directory <- function(dirname) !is.na(file.info(dirname)$isdir)


mcdir <- function(dirname){
    if(!file.exists(dirname)){
        dir.create(dirname)
    }

    setwd(dirname)
}

locload <- function(fileName) local(get(load(fileName)))


Holger Brandl's avatar
Holger Brandl committed
452
## tbd: it would be more efficient to use Reduce here (see http://stackoverflow.com/questions/34344214/how-to-join-multiple-data-frames-using-dplyr)
Holger Brandl's avatar
Holger Brandl committed
453 454 455 456 457 458 459 460 461 462
rmerge <- function(LDF, by, ...){
    DF <- LDF[[1]]
    for (i in 2:length(LDF)) {
        DF <- merge(DF, LDF[[i]], by=by)
    }
    DF
}



Holger Brandl's avatar
Holger Brandl committed
463 464
## Deprecated: use trim_ext instead
trimEnd <- function(fileNames, ...) trim_ext(fileNames, ...)
Holger Brandl's avatar
Holger Brandl committed
465

Holger Brandl's avatar
Holger Brandl committed
466
trim_ext <-function(fileNames, exts=c()){
Holger Brandl's avatar
Holger Brandl committed
467 468 469 470 471 472 473
    for(fileExt in exts){
        fileNames <- str_replace(fileNames, paste(fileExt, "$",sep=""), "")
    }

    fileNames
}

Holger Brandl's avatar
Holger Brandl committed
474
## DEPRECATED Use write_tsv instead
Holger Brandl's avatar
Holger Brandl committed
475 476
write.delim <- function(df, file, header=TRUE,...){
    write.table(df, file, row.names=FALSE, col.names=header, sep="\t", ...)
Holger Brandl's avatar
Holger Brandl committed
477 478 479 480 481 482 483 484 485 486
}

rmSomeElements <- function(vec, toDel) vec[!(vec %in% toDel)]

rmLastElement <- function(vec) vec[-length(vec)]


########################################################################################################################
## Memory management

Holger Brandl's avatar
Holger Brandl committed
487

Holger Brandl's avatar
Holger Brandl committed
488
# improved list of objects
Holger Brandl's avatar
Holger Brandl committed
489 490
lsos <- function (pos = 1, pattern, order.by, decreasing=FALSE, head=FALSE, n=5) {
    napply <- function(names, fn) sapply(names, function(x) fn(get(x, pos = pos)))
Holger Brandl's avatar
Holger Brandl committed
491
    names <- ls(pos = pos, pattern = pattern)
Holger Brandl's avatar
Holger Brandl committed
492

Holger Brandl's avatar
Holger Brandl committed
493 494 495 496 497
    obj.class <- napply(names, function(x) as.character(class(x))[1])
    obj.mode <- napply(names, mode)
    obj.type <- ifelse(is.na(obj.class), obj.mode, obj.class)
    obj.size <- napply(names, object.size)/1000000
    obj.dim <- t(napply(names, function(x)
Holger Brandl's avatar
Holger Brandl committed
498

499
    as.numeric(dim(x))[1:2]))
Holger Brandl's avatar
Holger Brandl committed
500 501
    vec <- is.na(obj.dim)[, 1] & (obj.type != "function")
    obj.dim[vec, 1] <- napply(names, length)[vec]
Holger Brandl's avatar
Holger Brandl committed
502

Holger Brandl's avatar
Holger Brandl committed
503 504
    out <- data.frame(obj.type, obj.size, obj.dim)
    names(out) <- c("Type", "Size", "Rows", "Columns")
Holger Brandl's avatar
Holger Brandl committed
505

Holger Brandl's avatar
Holger Brandl committed
506
    if (!missing(order.by))
507
    out <- out[order(out[[order.by]], decreasing=decreasing), ]
Holger Brandl's avatar
Holger Brandl committed
508 509 510

    if (head) out <- head(out, n)

Holger Brandl's avatar
Holger Brandl committed
511 512 513 514 515
    out <- transform(out, var_name=rownames(out))
    rownames(out) <- NULL
    arrange(out, Size)
}

Holger Brandl's avatar
Holger Brandl committed
516
# shorthand that just shows top 1 results
Holger Brandl's avatar
Holger Brandl committed
517 518 519 520
lsosh <- function(..., n=10) {
    lsos(..., order.by="Size", decreasing=TRUE, head=TRUE, n=n)
}

Holger Brandl's avatar
Holger Brandl committed
521 522 523 524 525 526 527 528 529 530
########################################################################################################################
### Statistics


## outlier handling
trim_outliers <- function(values, range=quantile(values, c(0.05, 0.95)))  pmax(range[1], pmin(range[2], values))

## use trim_outliers instead
#limit_range <- function(values, range)  pmax(range[1], pmin(range[2], values))

Holger Brandl's avatar
Holger Brandl committed
531
se <- function(x) sd(x, na.rm=TRUE) / sqrt(sum(!is.na(x)))
532 533 534 535 536 537 538 539


########################################################################################################################
### Misc

## inspired by http://stackoverflow.com/questions/8343509/better-error-message-for-stopifnot
assert <- function (expr, error) {
    if (! expr) stop(error, call. = FALSE)
540 541 542
}

### table rendering
Holger Brandl's avatar
Holger Brandl committed
543 544
table_browser <- function(df, caption=deparse(substitute(df)), ...){
    datatable(df, filter = "bottom", extensions = 'Buttons', options = list( dom = 'Bfrtip', buttons = c('copy', 'csv', 'excel')), caption=caption,...)
545
}
546

Holger Brandl's avatar
Holger Brandl committed
547 548 549 550
#results_prefix = "env_data_prep"
add_prefix = function(filename) {
    ## prefix a name with a project-prefix. Requires that results_prefix to be defined
    file.path(dirname(filename), paste0(results_prefix, ".", basename(filename)))
551 552
}