Showing posts with label R. Show all posts
Showing posts with label R. Show all posts

June 18, 2015

Useful links for plots

R:

Python:

February 14, 2014

How to find an euler cycle from a balanced directed graph in R

I was trying to find an euler cycle from a balanced (for every node, indegree=outdegree) directed graph in R. Firstly, I tried the PairViz package. However, it works only for undirected even (every node has even degree) graph. I posted in StackOverflow too, but I found that the solution is not readily available. So, I implemented the algorithm as below.



library(graph)

eulerCycle <- function(g, start=NULL){
  eulerCycle <- c()
  curNode <- ifelse(is.null(start), nodes(g)[1], start)
  
  while(!is.na(curNode)){
 cycle <- curNode
 while(!is.na(nextNode <- randomWalkNext(g, curNode))){
   g <- removeEdge(graph=g, from=curNode, to=nextNode)
   cycle <- append(cycle, nextNode)
   curNode <- nextNode
 }
 
 if(length(eulerCycle)==0){
   eulerCycle <- cycle
 }
 else{
   insertIndex <- which(eulerCycle==cycle[1])[1]
   eulerCycle <- append(eulerCycle,after=insertIndex,values=cycle[-1])
 }
 
 curNode <- getAnUnexploredNode(g, nodes=eulerCycle)
  }
  
  return(eulerCycle)
}

getAnUnexploredNode <- function(g, nodes){
  degrees <- degree(g, Nodes=nodes)
  nodeIndexes <- which(degrees$outDegree+degrees$inDegree>0)
  node <- NA
  if(length(nodeIndexes)>0){
 node <- nodes[nodeIndexes[1]]
  }
  return(node)
}

randomWalkNext <- function(g, from){
  outEdges <- edges(object=g, which=from)[[1]]
  nextNode <- NA
  if(length(outEdges)>0){
 nextNode <- outEdges[1]
  }
  return(nextNode)
}


Verification Code:

> g <- new("graphNEL", nodes=as.character(1:10), edgemode="directed")
> g <- addEdge(graph=g, from="1", to="10")
> g <- addEdge(graph=g, from="2", to="1")
> g <- addEdge(graph=g, from="2", to="6")
> g <- addEdge(graph=g, from="3", to="2")
> g <- addEdge(graph=g, from="4", to="2")
> g <- addEdge(graph=g, from="5", to="4")
> g <- addEdge(graph=g, from="6", to="5")
> g <- addEdge(graph=g, from="6", to="8")
> g <- addEdge(graph=g, from="7", to="9")
> g <- addEdge(graph=g, from="8", to="7")
> g <- addEdge(graph=g, from="9", to="6")
> g <- addEdge(graph=g, from="10", to="3")
> 
> ec <- eulerCycle(g, start="6")
> print(ec)
 [1] "6"  "5"  "4"  "2"  "1"  "10" "3"  "2"  "6"  "8"  "7"  "9"  "6" 


Update:

I have published a R package at CRAN, euler, to find eulerian paths from graphs.

January 24, 2014

Interface between R and PHP or other languages

RServe (link1, link2) is a useful R package to interface R with other languages like java, php, etc. It is basically a TCP/IP server. It creates tcp socket connections through which other the outside world can talk to R.

The good thing is it manages multiple connections in a clean way. It creates a separate workspace and a directory for every connections. So, each connection is independent of others. Another good thing is several client-side implementations are available including C/C++, Java, PHP.

Recently, I used it with PHP. It works great. You may start RServe as a daemon (using the function Rserve()) or from your R session with your current session available to all connections (using the function run.Rserve()).

While I was working on integrating R with PHP via Rserve, I was struggling to have write permission in the Rserve folder. I found that both Rserve and Apche Server have to be run by the same user and group. Both Apache and Rserve has to be configured for this purpose.

Apache Config:
1. Edit /etc/apache2/envvars 

export APACHE_RUN_USER=ashis
export APACHE_RUN_GROUP=ashis
2. You may have to change the ownership of the /var/locks/apache2 folder.

sudo chown -R ashis:ashis /var/locks/apache2/

Rserve config:
1. Find the uid and gid of the user (here ashis:ashis)

id ashis
2. Edit /etc/Rserve.conf file
uid UID_OF_USER
gid GID_OF_USER

Finally, You have to restart both apache and Rserve.

December 30, 2013

Simple try-catch code in R

Here is a simple code sample to demonstrate tryCatch function in R.


x <- tryCatch( "OK", 
          warning=function(w){     
            return(paste( "Warning:", conditionMessage(w)));
          }, 
          error = function(e) {      
            return(paste( "Error:", conditionMessage(e)));
          }, 
          finally={
            print("This is try-catch test. check the output.")
          });
print(x);

x <- tryCatch( warning("got a warning!"), 
               warning=function(w){     
                 return(paste( "Warning:", conditionMessage(w)));
               }, 
               error = function(e) {      
                 return(paste( "Error:", conditionMessage(e)));
               }, 
               finally={
                 print("This is try-catch test. check the output.")
               });
print(x);


x <- tryCatch( stop("an error occured!"), 
               warning=function(w){     
                 return(paste( "Warning:", conditionMessage(w)));
               }, 
               error = function(e) {      
                 return(paste( "Error:", conditionMessage(e)));
               }, 
               finally={
                 print("This is try-catch test. check the output.")
               });
print(x); 

December 28, 2013

Automatic mapping (or conversion) among different biological databases

biomaRt is an R package to map among different biological databases. Here is a simple code-snippet to convert human gene id to gene symbol.


library(biomaRt)
ensembl = useMart("ensembl",dataset="hsapiens_gene_ensembl")
symbols = getBM(attributes=c('entrezgene','hgnc_symbol'), filters='entrezgene', values=c("7157","5601"), mart=ensembl) 
 
Installation note:
  • In Ubuntu, you may need to install 'libxml2-dev' and 'libcurl4-openssl-dev'.

November 15, 2013

String Reverse in R

String reversing is a common operation especially in Bioinformatics. However, this function is not provided in R, not even in the "stringr" package. Here you can find the code:


str_reverse <- function(x){
  return(sapply(lapply(strsplit(x, NULL), rev), paste, collapse=""))
}

s <- "abc"
s1 <- str_reverse(s)
print(s1)

November 4, 2013

ROC (Receiver Operating Characteristics) Curve in R

There are 2 packages to calculate different measures and draw different graphs of ROC cureve.
  1. ROCR (http://rocr.bioinf.mpi-sb.mpg.de/)
  2. pROC (http://cran.r-project.org/web/packages/pROC/pROC.pdf)

Code to generate ROC curve and AUC (Area under the curve) value

Using ROCR:
 # generate ROC curve  
 pred <- prediction(scores, labels)  
 perf <- performance(pred, "tpr", "fpr")  
 plot(perf)  

 #calculate AUC value  
 aucPerf <- performance( pred, 'auc')  
 auc <- slot(aucPerf, "y.values")  

Using pROC:
 roc.obj <- roc(response=labels, predictor=scores)  
 plot(roc.obj)  
 auc(roc.obj)  

Convert a dataframe to a vector in R

It is not possible to convert a dataframe directly to a vector. However, a dataframe can first be converted to a matrix and then to a vector.

 as.vector(as.matrix(myDataFrame))  

July 17, 2013

How to build package in R

There is an excellent video tutorial on building package in R. The whole tutorial contains 6 short videos. I have been so impressed that I have made a playlist of my own. Here is the playlist link:

http://www.youtube.com/playlist?list=PLdvICbjqfRbdrX16ZKqq4HsKRaq4r_xSz

Enjoy R!

March 28, 2013

Clear all memory in R

There are several steps to clear all memory in R.

Step-1: Clear all variables from the workspace.
rm(list=ls(all=TRUE))


Note: if all=TRUE option ls function ensures to get all variables (even imported by other packages).

Step-2: Call garbage collector.
gc()

March 22, 2013

R subsetting may convert a dataframe into a vector

The common way of subsetting in R is to give the row or column indexes inside brackets ([rows,cols]). One notable property of this type of
However, users generally


March 20, 2013

Install R in ubuntu from command line

 Steps to install R in ubuntu from command line:
  1. add the following configuration in /etc/apt/sources.list file
    # configuration for R
    deb http://cran.nexr.com/bin/linux/ubuntu precise/
  2. Command: sudo apt-get update
  3. Command: sudo apt-get install r-base
  4.  Command to start R: R
  5. Command to quit R: q()

NOTE:

1) Step-1 is dependent on the version of ubuntu. You can find the ubuntu version using the following command:

 lsb_release -a

2) You can also different mirror site for step-1. The list is available here.

3) You may need to use secure apt. In that case, just after step-1 (before step-2), run the following commands:

gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys E084DAB9
 gpg -a --export E084DAB9 | sudo apt-key add - 
 





 
Reference: http://cran.r-project.org/bin/linux/ubuntu/README

July 20, 2012

Learning R and Bioconductor

R is a powerful statistical tool which is heavily used in bioinformatics. Bioconductor, a very useful tool for high throughput genomic data analysis, has been developed using R. Here are two important links for learning R and Bioconductor.
  1. http://www.cyclismo.org/tutorial/R/index.html
  2. http://manuals.bioinformatics.ucr.edu/home/R_BioCondManual

Besides, the lectures by Dr. Roger D Peng, Associate Professor, Johns Hopkins University in the Computing for Data Analysis course are very helpful. The lectures are available in youtube - http://www.youtube.com/watch?v=EiKxy5IecUw&list=PL7Tw2kQ2edvr2lv8FTvg9msf8YHQz0MS0

Happy learning!