mercredi 21 novembre 2012

R  code  for listing directories/code R pour lister les repertoires


Here is a pretty R  code  for listing directories in a given directory
Voici un code R pour lister les repertoires d'un dossier donné
list.dirs <- function(path=".",recursive=FALSE) {
    get.list <- list.files(path)
    if (length(get.list) == 0) {return(NULL)} #no files or directories
    get.list.fixed <- paste(path,get.list,sep="/")
    whichonesaredir <- file.info(get.list.fixed)$isdir
    if (!any(whichonesaredir)) {return(NULL)} #no directories, only files
    dirlist <- get.list.fixed[whichonesaredir]
    finaldirlist <- dirlist
    if ((recursive & length(dirlist) > 0)) {
      for (i in 1:length(dirlist)) {
         finaldirlist <- c(finaldirlist,list.dirs(dirlist[i],recursive))
      }
    }
    return(finaldirlist)
}
Save the code in a file (listDir.r for example) and in R console use the following commands  
source('listDir.r') #to source the file
list=list.dirs(path,rec)#path is the current path by default else the dir in path will be listed. 
#rec (TRUE or FALSE(defaulty)) indicates if the sub-directories will be listed or not


mercredi 26 septembre 2012

simple way to compute rmse root mean square error in R

calculer rmse ("racine" de l'erreur moyenne quadratique) avec R.

rmse=function(obs,pred)
{
    diff=obs-pred
    diff=diff[!is.na(diff)]  #to remove NA values
    return (sqrt(mean((diff)^2)))
}

save the commands above in a file named rmse.r
To call this function:
       considering that obs is the array of observed values, pred is the array of predicted values
do

source("rmse.r")
rmsErr= rmse(obs,pred)

jeudi 23 août 2012

plot two histograms together in R

Considering two samples of datas A and B. To plot histograms together in the same window 
just run the following commands (in the R Console) 
 
hist(A,col="red")
hist(B, col="blue",add=T)
 
Example: 
 
b=rnorm(2000, 6, 1)
a=rnorm(2000, 3, 1)
hist(a,col="red",ylim=c(0,400))
hist(b,col="blue",ylim=c(0,400),add=T)  # add=T is the key