core_commons.R 9.53 KB
Newer Older
Holger Brandl's avatar
Holger Brandl committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
########################################################################################################################
## set a default cran r mirror  and customize environment

#cat(".Rprofile: Setting Goettingen repository\n")
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)

# for sqldf to avoid the use of tckl
options(gsubfn.engine = "R")

Holger Brandl's avatar
Holger Brandl committed
20

Holger Brandl's avatar
Holger Brandl committed
21
########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
22
## automatic package installation
Holger Brandl's avatar
Holger Brandl committed
23

24
require_auto <-  function(x){
Holger Brandl's avatar
Holger Brandl committed
25 26 27 28 29
    x <- as.character(substitute(x))

    if(isTRUE(x %in% .packages(all.available=TRUE))) {
        eval(parse(text=paste("require(", x, ",  quietly=T)", sep="")))
    } else {
30
        #        update.packages(ask=F) # update dependencies, if any.
Holger Brandl's avatar
Holger Brandl committed
31 32 33 34 35 36 37
        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")
38
        #        biocLite(character(), ask=FALSE) # update dependencies, if any.
39
        eval(parse(text=paste("biocLite('", x, "', ask=FALSE)", sep="")))
Holger Brandl's avatar
Holger Brandl committed
40 41 42 43
        eval(parse(text=paste("require(", x, ",  quietly=T)", sep="")))
    }
}

44 45 46 47 48 49
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
50

Holger Brandl's avatar
Holger Brandl committed
51
########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
52
## load core packages
Holger Brandl's avatar
Holger Brandl committed
53

54 55 56 57
require_auto(plyr)
require_auto(stringr)
require_auto(reshape2)
#require_auto(reshape2, quietly=T, warn.conflicts=F)
Holger Brandl's avatar
Holger Brandl committed
58

Holger Brandl's avatar
Holger Brandl committed
59
## load on purpose after plyr
60 61 62
require_auto(dplyr)
require_auto(magrittr)
require_auto(tidyr)
63

Holger Brandl's avatar
Holger Brandl committed
64
## needed for caching
65
require_auto(digest)
Holger Brandl's avatar
Holger Brandl committed
66
require_auto(readr)
67 68 69 70 71 72 73 74
require_auto(readxl)


## common plotting requirements since they are omnipresent
require_auto(ggplot2)
require_auto(scales)
require_auto(grid)

Holger Brandl's avatar
Holger Brandl committed
75 76

## moved into datatable_commons because replaced almost everywhere with dplyr
77
#require_auto(data.table)
Holger Brandl's avatar
Holger Brandl committed
78 79 80 81 82




########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
83
#### Convenience aliases
Holger Brandl's avatar
Holger Brandl committed
84 85


Holger Brandl's avatar
Holger Brandl committed
86
echo <- function(...) cat(paste(...), fill=T)
Holger Brandl's avatar
Holger Brandl committed
87 88 89 90

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

# string concatenation without space gaps (could/should use paste0 instead)
Holger Brandl's avatar
Holger Brandl committed
91 92
## Deprecated: use paste0 instead
#concat <- function(...) paste(..., sep="")
Holger Brandl's avatar
Holger Brandl committed
93 94 95 96 97

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

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

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

Holger Brandl's avatar
Holger Brandl committed
100

Holger Brandl's avatar
Holger Brandl committed
101 102 103 104 105 106 107 108 109 110
########################################################################################################################
#### 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
111 112 113
#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
114 115 116 117 118

rownames2column <- function(df, colname){
    df <- as.df(df)
    df$tttt <- rownames(df);
    rownames(df) <- NULL;
Holger Brandl's avatar
Holger Brandl committed
119
    plyr::rename(df, c(tttt=colname))
Holger Brandl's avatar
Holger Brandl committed
120 121 122 123
}


column2rownames<- function(df, colname){
124
    #browser()
Holger Brandl's avatar
Holger Brandl committed
125 126 127
    ## force into df to avoid dplyr problems
    df <- as.df(df)

Holger Brandl's avatar
Holger Brandl committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    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
144 145
#http://astrostatistics.psu.edu/datasets/R/html/base/html/formals.html
set_names <- function(df, ...){
146
    #browser()
Holger Brandl's avatar
Holger Brandl committed
147
    newnames <- as.character(unlist(list(...)))
148 149 150 151

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

152
    names(df) <- newnames;
Holger Brandl's avatar
Holger Brandl committed
153 154
    return(df)
}
Holger Brandl's avatar
Holger Brandl committed
155 156
#iris %>% set_names(c("setosa", "hallo")) %>% head
#iris %>% set_names("setosa", "hallo") %>% head
Holger Brandl's avatar
Holger Brandl committed
157 158


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

Holger Brandl's avatar
Holger Brandl committed
161 162
print_head <- function(df, desc=NULL){
    print(head(df))
Holger Brandl's avatar
Holger Brandl committed
163
    print(nrow(df))
Holger Brandl's avatar
Holger Brandl committed
164 165 166 167 168 169
    return(df)
}


fac2char <- function(mydata, convert=names(mydata)[sapply(mydata, is.factor)]){
    if(length(convert)==0)
170
    return(mydata)
Holger Brandl's avatar
Holger Brandl committed
171 172 173 174 175 176 177 178 179 180 181 182 183

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

Holger Brandl's avatar
Holger Brandl committed
187

Holger Brandl's avatar
Holger Brandl committed
188 189

safe_ifelse <- function(cond, yes, no) {
190 191
    class.y <- class(yes)
    if ("factor" %in% class.y) {  # Note the small condition change here
Holger Brandl's avatar
Holger Brandl committed
192
    levels.y = levels(yes)
193 194 195
    }
    X <- ifelse(cond,yes,no)
    if ("factor" %in% class.y) {  # Note the small condition change here
Holger Brandl's avatar
Holger Brandl committed
196 197
    X = as.factor(X)
    levels(X) = levels.y
198 199 200 201
    } else {
        class(X) <- class.y
    }
    return(X)
Holger Brandl's avatar
Holger Brandl committed
202 203 204 205 206 207 208
}

## for na instead use mutate_each with:
empty_as_na <- function(x) safe_ifelse(x=="", NA, x)
## see http://stackoverflow.com/questions/24172111/change-the-blank-cells-to-na/33952598#33952598


209 210 211 212 213 214 215
reload_dplyr <- function(){
    unloadNamespace('tidyr')
    unloadNamespace('dplyr')
    require(tidyr);require(dplyr)
}


Holger Brandl's avatar
Holger Brandl committed
216 217


Holger Brandl's avatar
Holger Brandl committed
218 219 220 221
## workaround for biomart
## Deprecated: load dplyr after biomart to avoid this problem
#dselect <- function(...) dplyr::select(...)

Holger Brandl's avatar
Holger Brandl committed
222

Holger Brandl's avatar
Holger Brandl committed
223
########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
224
#### Result Caching for long running tasks
Holger Brandl's avatar
Holger Brandl committed
225

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

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

Holger Brandl's avatar
Holger Brandl committed
231 232 233 234 235 236 237 238 239 240 241
    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
242 243
#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
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

########################################################################################################################
#### 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)))


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
272 273
## Deprecated: use trim_ext instead
trimEnd <- function(fileNames, ...) trim_ext(fileNames, ...)
Holger Brandl's avatar
Holger Brandl committed
274

Holger Brandl's avatar
Holger Brandl committed
275
trim_ext <-function(fileNames, exts=c()){
Holger Brandl's avatar
Holger Brandl committed
276 277 278 279 280 281 282
    for(fileExt in exts){
        fileNames <- str_replace(fileNames, paste(fileExt, "$",sep=""), "")
    }

    fileNames
}

Holger Brandl's avatar
Holger Brandl committed
283
## DEPRECATED Use write_tsv instead
Holger Brandl's avatar
Holger Brandl committed
284 285
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
286 287 288 289 290 291 292 293 294 295
}

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

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


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

Holger Brandl's avatar
Holger Brandl committed
296

Holger Brandl's avatar
Holger Brandl committed
297 298
# improved list of objects
lsos <- function (pos = 1, pattern, order.by,
299
decreasing=FALSE, head=FALSE, n=5) {
Holger Brandl's avatar
Holger Brandl committed
300
    napply <- function(names, fn) sapply(names, function(x)
301
    fn(get(x, pos = pos)))
Holger Brandl's avatar
Holger Brandl committed
302 303 304 305 306 307
    names <- ls(pos = pos, pattern = pattern)
    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)
308
    as.numeric(dim(x))[1:2]))
Holger Brandl's avatar
Holger Brandl committed
309 310 311 312 313
    vec <- is.na(obj.dim)[, 1] & (obj.type != "function")
    obj.dim[vec, 1] <- napply(names, length)[vec]
    out <- data.frame(obj.type, obj.size, obj.dim)
    names(out) <- c("Type", "Size", "Rows", "Columns")
    if (!missing(order.by))
314
    out <- out[order(out[[order.by]], decreasing=decreasing), ]
Holger Brandl's avatar
Holger Brandl committed
315
    if (head)
316 317
    out <- head(out, n)
    #        out
Holger Brandl's avatar
Holger Brandl committed
318 319 320 321 322
    out <- transform(out, var_name=rownames(out))
    rownames(out) <- NULL
    arrange(out, Size)
}

Holger Brandl's avatar
Holger Brandl committed
323
# shorthand that just shows top 1 results
Holger Brandl's avatar
Holger Brandl committed
324 325 326 327
lsosh <- function(..., n=10) {
    lsos(..., order.by="Size", decreasing=TRUE, head=TRUE, n=n)
}

Holger Brandl's avatar
Holger Brandl committed
328 329 330 331 332 333 334 335 336 337
########################################################################################################################
### 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))

338
se<-function(x)    sd(x, na.rm=TRUE) / sqrt(sum(!is.na(x)))