core_commons.R 6.47 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 20 21 22

## automatic package installation
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
23 24 25 26 27 28 29 30 31 32 33
#qlibrary <- function(libname) {library(as.character(substitute(libname)), quietly=T, warn.conflicts=F, character.only=T )}

## set a default cran r mirror
#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)


## load core packages
Holger Brandl's avatar
Holger Brandl committed
34 35 36 37 38
require.auto(plyr)
require.auto(stringr)
require.auto(reshape2)
#require.auto(reshape2, quietly=T, warn.conflicts=F)

Holger Brandl's avatar
Holger Brandl committed
39
## load on purpose after plyr
Holger Brandl's avatar
Holger Brandl committed
40 41
require.auto(dplyr)

42 43
require.auto(magrittr)

Holger Brandl's avatar
Holger Brandl committed
44 45
#require.auto(data.table)

Holger Brandl's avatar
Holger Brandl committed
46
## user browser for help
Holger Brandl's avatar
Holger Brandl committed
47
options(help_type="html")
Holger Brandl's avatar
Holger Brandl committed
48 49

## plot more characters per line
Holger Brandl's avatar
Holger Brandl committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
options(width=150)

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






########################################################################################################################
#### Small aliases


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


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

qns <- function() quit(save="no")


# string concatenation without space gaps (could/should use paste0 instead)
concat <- function(...) paste(..., sep="")


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

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

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


Holger Brandl's avatar
Holger Brandl committed
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
########################################################################################################################
#### data.frame manipulation

subsample <- function(df, sampleSize, ...){
    df[sample(1:nrow(df), min(sampleSize, nrow(df)), ...),]
}

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

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

as.df <- function(dt) as.data.frame(dt)



rownames2column <- function(df, colname){
    df <- as.df(df)
    df$tttt <- rownames(df);
    rownames(df) <- NULL;
Holger Brandl's avatar
Holger Brandl committed
103
    plyr::rename(df, c(tttt=colname))
Holger Brandl's avatar
Holger Brandl committed
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 131 132 133
}


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
134
    print(nrow(df))
Holger Brandl's avatar
Holger Brandl committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    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
155
## replace R within pipe change just use ... %>% do(replaceNA(0)) %>% ...
Holger Brandl's avatar
Holger Brandl committed
156
replaceNA <- function(x, withValue) { x[is.na(x)] <- withValue; x }
Holger Brandl's avatar
Holger Brandl committed
157

Holger Brandl's avatar
Holger Brandl committed
158 159 160 161 162

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

Holger Brandl's avatar
Holger Brandl committed
163 164 165 166
## outlier handling
trim_outliers <- function(values, range=quantile(values, c(0.05, 0.95)))  pmax(range[1], pmin(range[2], values))

limit_range <- function(values, range)  pmax(range[1], pmin(range[2], values))
Holger Brandl's avatar
Holger Brandl committed
167 168


Holger Brandl's avatar
Holger Brandl committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

########################################################################################################################
#### 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
198
trim_ext <- function(fileNames, ...) trimEnd(fileNames, ...)
Holger Brandl's avatar
Holger Brandl committed
199 200 201 202 203 204 205 206
trimEnd <-function(fileNames, exts=c()){
    for(fileExt in exts){
        fileNames <- str_replace(fileNames, paste(fileExt, "$",sep=""), "")
    }

    fileNames
}

Holger Brandl's avatar
Holger Brandl committed
207 208
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
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
}

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

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


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

## Memory management

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

# shorthand
lsosh <- function(..., n=10) {
    lsos(..., order.by="Size", decreasing=TRUE, head=TRUE, n=n)
}