core_commons.R 7.78 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

Holger Brandl's avatar
Holger Brandl committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
require.auto <-  function(x){
    x <- as.character(substitute(x))

    if(isTRUE(x %in% .packages(all.available=TRUE))) {
        eval(parse(text=paste("require(", x, ",  quietly=T)", sep="")))
    } else {
    #        update.packages(ask=F) # update dependencies, if any.
        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")
        biocLite(character(), ask=FALSE) # update dependencies, if any.
        eval(parse(text=paste("biocLite('", x, "')", sep="")))
        eval(parse(text=paste("require(", x, ",  quietly=T)", sep="")))
    }
}

Holger Brandl's avatar
Holger Brandl committed
44

Holger Brandl's avatar
Holger Brandl committed
45
########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
46
## load core packages
Holger Brandl's avatar
Holger Brandl committed
47

Holger Brandl's avatar
Holger Brandl committed
48 49 50 51 52
require.auto(plyr)
require.auto(stringr)
require.auto(reshape2)
#require.auto(reshape2, quietly=T, warn.conflicts=F)

Holger Brandl's avatar
Holger Brandl committed
53
## load on purpose after plyr
Holger Brandl's avatar
Holger Brandl committed
54
require.auto(dplyr)
55
require.auto(magrittr)
56
require.auto(tidyr)
57

Holger Brandl's avatar
Holger Brandl committed
58 59 60 61 62 63
#require.auto(data.table)




########################################################################################################################
Holger Brandl's avatar
Holger Brandl committed
64
#### Convenience aliases
Holger Brandl's avatar
Holger Brandl committed
65 66 67 68 69 70 71


echo <- function(...) print(paste(...))

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

# string concatenation without space gaps (could/should use paste0 instead)
Holger Brandl's avatar
Holger Brandl committed
72 73
## Deprecated: use paste0 instead
#concat <- function(...) paste(..., sep="")
Holger Brandl's avatar
Holger Brandl committed
74 75 76 77 78

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

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

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

Holger Brandl's avatar
Holger Brandl committed
81

Holger Brandl's avatar
Holger Brandl committed
82 83 84 85 86 87 88 89 90 91
########################################################################################################################
#### 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
92 93 94
#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
95 96 97 98 99

rownames2column <- function(df, colname){
    df <- as.df(df)
    df$tttt <- rownames(df);
    rownames(df) <- NULL;
Holger Brandl's avatar
Holger Brandl committed
100
    plyr::rename(df, c(tttt=colname))
Holger Brandl's avatar
Holger Brandl committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
}


column2rownames<- function(df, colname){
#browser()
    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))]
}


set_names <- function(df, newnames){
    df<- as.df(df)
    names(df) <- newnames;
    return(df)
}


print_head <- function(df, desc=NULL){
    print(head(df))
Holger Brandl's avatar
Holger Brandl committed
131
    print(nrow(df))
Holger Brandl's avatar
Holger Brandl committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    return(df)
}


fac2char <- function(mydata, convert=names(mydata)[sapply(mydata, is.factor)]){
    if(length(convert)==0)
        return(mydata)

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

Holger Brandl's avatar
Holger Brandl committed
155 156 157 158 159

## workaround for biomart
## Deprecated: load dplyr after biomart to avoid this problem
#dselect <- function(...) dplyr::select(...)

Holger Brandl's avatar
Holger Brandl committed
160

Holger Brandl's avatar
Holger Brandl committed
161 162
########################################################################################################################
#### Result Caching for long running
Holger Brandl's avatar
Holger Brandl committed
163

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

Holger Brandl's avatar
Holger Brandl committed
166
cache_it <- function(expr, cacheName=paste0("cache_", substr(digest::digest(expr), 1,6))){
Holger Brandl's avatar
Holger Brandl committed
167
    cacheFile <- paste0(".", cacheName, ".RData")
Holger Brandl's avatar
Holger Brandl committed
168

Holger Brandl's avatar
Holger Brandl committed
169 170 171 172 173 174 175 176 177 178 179
    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
180 181
#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
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

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

Holger Brandl's avatar
Holger Brandl committed
213
trim_ext <-function(fileNames, exts=c()){
Holger Brandl's avatar
Holger Brandl committed
214 215 216 217 218 219 220
    for(fileExt in exts){
        fileNames <- str_replace(fileNames, paste(fileExt, "$",sep=""), "")
    }

    fileNames
}

Holger Brandl's avatar
Holger Brandl committed
221 222
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
223 224 225 226 227 228 229 230 231 232
}

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

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


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

Holger Brandl's avatar
Holger Brandl committed
233

Holger Brandl's avatar
Holger Brandl committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
# improved list of objects
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)))
    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)
                        as.numeric(dim(x))[1:2]))
    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))
        out <- out[order(out[[order.by]], decreasing=decreasing), ]
    if (head)
        out <- head(out, n)
#        out
    out <- transform(out, var_name=rownames(out))
    rownames(out) <- NULL
    arrange(out, Size)
}

Holger Brandl's avatar
Holger Brandl committed
260
# shorthand that just shows top 1 results
Holger Brandl's avatar
Holger Brandl committed
261 262 263 264
lsosh <- function(..., n=10) {
    lsos(..., order.by="Size", decreasing=TRUE, head=TRUE, n=n)
}

Holger Brandl's avatar
Holger Brandl committed
265 266 267 268 269 270 271 272 273 274 275
########################################################################################################################
### 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))

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