core_commons.R 12.5 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 22 23 24
## 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
options(dplyr.print_max = 20) ## num rows
options(dplyr.width = 130) ## width

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

Holger Brandl's avatar
Holger Brandl committed
28

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

32
require_auto <-  function(x){
33 34
    warning("require_auto is deprecated, use loadpack() instead")

Holger Brandl's avatar
Holger Brandl committed
35 36 37 38 39
    x <- as.character(substitute(x))

    if(isTRUE(x %in% .packages(all.available=TRUE))) {
        eval(parse(text=paste("require(", x, ",  quietly=T)", sep="")))
    } else {
40
        #        update.packages(ask=F) # update dependencies, if any.
Holger Brandl's avatar
Holger Brandl committed
41 42 43 44 45 46 47
        eval(parse(text=paste("install.packages('", x, "')", sep="")))
    }

    if(isTRUE(x %in% .packages(all.available=TRUE))) {
        eval(parse(text=paste("require(", x, ",  quietly=T)", sep="")))
    } else {
        source("http://bioconductor.org/biocLite.R")
48
        #        biocLite(character(), ask=FALSE) # update dependencies, if any.
49
        eval(parse(text=paste("biocLite('", x, "', ask=FALSE)", sep="")))
Holger Brandl's avatar
Holger Brandl committed
50 51 52 53
        eval(parse(text=paste("require(", x, ",  quietly=T)", sep="")))
    }
}

54 55
## externalized installer to also allow for installation without loading
.instpack <- function(x){
56 57 58 59 60 61 62 63 64 65 66 67 68 69
    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="")))
        }
    }
70 71 72 73 74 75
}

loadpack <-  function(x, warn_conflicts=T){
    x <- as.character(substitute(x));

   .instpack(x)
76 77

    ## load it using a library function so that loadpack errors if package is still not ins
Holger Brandl's avatar
Holger Brandl committed
78
    eval(parse(text=paste("library(", x, ",  quietly=T, warn.conflicts=", warn_conflicts, ")", sep="")))
79 80
}

81 82 83 84 85 86
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
87

Holger Brandl's avatar
Holger Brandl committed
88
########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
89
## load core packages
Holger Brandl's avatar
Holger Brandl committed
90

91 92 93
loadpack(plyr)
loadpack(stringr)
loadpack(reshape2)
94
#loadpack(reshape2, quietly=T, warn_conflicts=F)
Holger Brandl's avatar
Holger Brandl committed
95

Holger Brandl's avatar
Holger Brandl committed
96
## load on purpose after plyr
97 98 99
loadpack(dplyr, warn_conflicts=F)
loadpack(magrittr, warn_conflicts=F)
loadpack(tidyr, warn_conflicts=F)
100

Holger Brandl's avatar
Holger Brandl committed
101
## needed for caching
102 103 104 105
loadpack(digest)
loadpack(readr)
suppressWarnings(loadpack(readxl)) ## supress differring build number
#loadpack(readxl) ## supress differring build number
106 107 108


## common plotting requirements since they are omnipresent
109
loadpack(ggplot2)
110
loadpack(scales, warn_conflicts=F)
111
loadpack(grid)
112

Holger Brandl's avatar
Holger Brandl committed
113
## for table exploration without using Rstudio
114
loadpack(DT)
Holger Brandl's avatar
Holger Brandl committed
115

Holger Brandl's avatar
Holger Brandl committed
116 117

## moved into datatable_commons because replaced almost everywhere with dplyr
118
#loadpack(data.table)
Holger Brandl's avatar
Holger Brandl committed
119 120 121 122 123




########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
124
#### Convenience aliases
Holger Brandl's avatar
Holger Brandl committed
125 126


Holger Brandl's avatar
Holger Brandl committed
127
echo <- function(...) cat(paste(...), fill=T)
Holger Brandl's avatar
Holger Brandl committed
128 129 130 131

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

# string concatenation without space gaps (could/should use paste0 instead)
Holger Brandl's avatar
Holger Brandl committed
132 133
## Deprecated: use paste0 instead
#concat <- function(...) paste(..., sep="")
Holger Brandl's avatar
Holger Brandl committed
134 135 136 137 138

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

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

Holger Brandl's avatar
Holger Brandl committed
139 140
as.df <- function(dt) as.data.frame(dt)

Holger Brandl's avatar
Holger Brandl committed
141

Holger Brandl's avatar
Holger Brandl committed
142 143 144 145 146 147 148 149 150 151
########################################################################################################################
#### 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
152 153 154
#vec2df <- function(namedVec) namedVec %>% {data.frame(name=names(.), value=., row.names=NULL)}
vec2df <- function(namedVec) data.frame(name=names(namedVec), value=namedVec, row.names=NULL)

Holger Brandl's avatar
Holger Brandl committed
155 156

rownames2column <- function(df, colname){
157 158
    warning("DEPRECATED Use dplyr::add_rownames directly")
    add_rownames(df, var=colname)
Holger Brandl's avatar
Holger Brandl committed
159 160 161 162
}


column2rownames<- function(df, colname){
163
    #browser()
Holger Brandl's avatar
Holger Brandl committed
164 165 166
    ## force into df to avoid dplyr problems
    df <- as.df(df)

Holger Brandl's avatar
Holger Brandl committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    rownames(df) <- ac(df[,colname])
    df[colname] <- NULL
    return(df)
}

## pushing some columns to the right end of a data.frame
push_right <- function(df, pushColNames){
    df[,c(setdiff(names(df),pushColNames), pushColNames)]
}


push_left <- function(df, pushColNames){
    df[,c(pushColNames, setdiff(names(df),pushColNames))]
}


Holger Brandl's avatar
Holger Brandl committed
183 184
#http://astrostatistics.psu.edu/datasets/R/html/base/html/formals.html
set_names <- function(df, ...){
185
    #browser()
Holger Brandl's avatar
Holger Brandl committed
186
    newnames <- as.character(unlist(list(...)))
187 188 189 190

    ## automatically convert matrices to data.frames (otherwise the names set would fail
    if(is.matrix(df)) df %<>% as.data.frame()

191
    names(df) <- newnames;
Holger Brandl's avatar
Holger Brandl committed
192 193
    return(df)
}
Holger Brandl's avatar
Holger Brandl committed
194 195
#iris %>% set_names(c("setosa", "hallo")) %>% head
#iris %>% set_names("setosa", "hallo") %>% head
Holger Brandl's avatar
Holger Brandl committed
196 197


198 199 200 201 202 203 204
rify_names  <- function(df){
    warning("DEPRECATED: use pretty_columns instead");
    names(df) <- names(df) %>% str_replace_all(c(" "="_", "-"="_"));
    df
}

pretty_columns  <- function(df){ names(df) <- names(df) %>% str_replace_all(c(" "="_", "-"="_", "[.]"="_")) %>% tolower; df}
Holger Brandl's avatar
Holger Brandl committed
205 206


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

Holger Brandl's avatar
Holger Brandl committed
209 210
print_head <- function(df, desc=NULL){
    print(head(df))
Holger Brandl's avatar
Holger Brandl committed
211
    print(nrow(df))
Holger Brandl's avatar
Holger Brandl committed
212 213 214 215 216
    return(df)
}


fac2char <- function(mydata, convert=names(mydata)[sapply(mydata, is.factor)]){
Holger Brandl's avatar
Holger Brandl committed
217 218 219
    if(length(convert)==0){
        return(mydata)
    }
Holger Brandl's avatar
Holger Brandl committed
220 221 222 223 224 225 226 227 228 229 230 231 232

    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
233
## replace R within pipe change just use ... %>% do(replaceNA(0)) %>% ...
Holger Brandl's avatar
Holger Brandl committed
234
replaceNA <- function(x, withValue) { x[is.na(x)] <- withValue; x }
Holger Brandl's avatar
Holger Brandl committed
235

Holger Brandl's avatar
Holger Brandl committed
236

Holger Brandl's avatar
Holger Brandl committed
237

Holger Brandl's avatar
Holger Brandl committed
238
## todo still needed
Holger Brandl's avatar
Holger Brandl committed
239
safe_ifelse <- function(cond, yes, no) {
Holger Brandl's avatar
Holger Brandl committed
240 241 242 243 244 245
#browser()
    isfacOrChar <- function(x) class(x)  %in% c("factor", "character")

    if (isfacOrChar(yes) | isfacOrChar(no)) {
        yes <- ac(yes)
        no <- ac(no)
246
    }
Holger Brandl's avatar
Holger Brandl committed
247 248

    ifelse(cond,yes,no)
Holger Brandl's avatar
Holger Brandl committed
249 250
}

Holger Brandl's avatar
Holger Brandl committed
251

Holger Brandl's avatar
Holger Brandl committed
252
## for na instead use mutate_each with:
Holger Brandl's avatar
Holger Brandl committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
#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
281 282 283
## see http://stackoverflow.com/questions/24172111/change-the-blank-cells-to-na/33952598#33952598


284 285 286 287 288 289 290
reload_dplyr <- function(){
    unloadNamespace('tidyr')
    unloadNamespace('dplyr')
    require(tidyr);require(dplyr)
}


Holger Brandl's avatar
Holger Brandl committed
291 292


Holger Brandl's avatar
Holger Brandl committed
293 294 295 296
## workaround for biomart
## Deprecated: load dplyr after biomart to avoid this problem
#dselect <- function(...) dplyr::select(...)

Holger Brandl's avatar
Holger Brandl committed
297

Holger Brandl's avatar
Holger Brandl committed
298
########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
299
#### Result Caching for long running tasks
Holger Brandl's avatar
Holger Brandl committed
300

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

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

Holger Brandl's avatar
Holger Brandl committed
306 307 308 309 310 311 312 313 314 315 316
    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
317 318
#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
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336

########################################################################################################################
#### 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
337
## 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
338 339 340 341 342 343 344 345 346 347
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
348 349
## Deprecated: use trim_ext instead
trimEnd <- function(fileNames, ...) trim_ext(fileNames, ...)
Holger Brandl's avatar
Holger Brandl committed
350

Holger Brandl's avatar
Holger Brandl committed
351
trim_ext <-function(fileNames, exts=c()){
Holger Brandl's avatar
Holger Brandl committed
352 353 354 355 356 357 358
    for(fileExt in exts){
        fileNames <- str_replace(fileNames, paste(fileExt, "$",sep=""), "")
    }

    fileNames
}

Holger Brandl's avatar
Holger Brandl committed
359
## DEPRECATED Use write_tsv instead
Holger Brandl's avatar
Holger Brandl committed
360 361
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
362 363 364 365 366 367 368 369 370 371
}

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

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


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

Holger Brandl's avatar
Holger Brandl committed
372

Holger Brandl's avatar
Holger Brandl committed
373
# improved list of objects
Holger Brandl's avatar
Holger Brandl committed
374 375
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
376
    names <- ls(pos = pos, pattern = pattern)
Holger Brandl's avatar
Holger Brandl committed
377

Holger Brandl's avatar
Holger Brandl committed
378 379 380 381 382
    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
383

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

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

Holger Brandl's avatar
Holger Brandl committed
391
    if (!missing(order.by))
392
    out <- out[order(out[[order.by]], decreasing=decreasing), ]
Holger Brandl's avatar
Holger Brandl committed
393 394 395

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

Holger Brandl's avatar
Holger Brandl committed
396 397 398 399 400
    out <- transform(out, var_name=rownames(out))
    rownames(out) <- NULL
    arrange(out, Size)
}

Holger Brandl's avatar
Holger Brandl committed
401
# shorthand that just shows top 1 results
Holger Brandl's avatar
Holger Brandl committed
402 403 404 405
lsosh <- function(..., n=10) {
    lsos(..., order.by="Size", decreasing=TRUE, head=TRUE, n=n)
}

Holger Brandl's avatar
Holger Brandl committed
406 407 408 409 410 411 412 413 414 415
########################################################################################################################
### 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
416
se <- function(x) sd(x, na.rm=TRUE) / sqrt(sum(!is.na(x)))
417 418 419 420 421 422 423 424 425


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

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