Friday, 30 January 2015

Directory & File Management

Managing directory from R becomes handy when automating batch processes, and helps with managing disk spaces when extracting and manipulating large volumes of data.


To check contents of the current (working) directory:

dir()



To obtain more information about the directory or files:

file.info(dir())  
  
file.info("home/document/folder_name")   



To set working directory:

setwd("home/document/folder_name")



To identify path to the current (working) directory:

getwd()



To create a new directory (you can only specify the file name if you are creating the new directory within the working directory):

dir.create("home/document/folder_name")
   

To create a new file:

file.create("FILE.txt")  



To create a temporary file or directory:

tempfile()  
  


To remove all files in a directory:

unlink("home/document/folder_name/*")



To delete a directory (you need to ensure that the directory you are trying to delete is not set as the working directory):

unlink("home/document/folder_name",recursive=TRUE)




To remove a file:

file.remove("home/document/folder_name/file_name.txt")



To check if a certain file exists:

file.exists("home/document/folder_name/file_name.txt")



To select files in the directory using wildcard:

Sys.glob("M*")  



To copy a file from one directory to another:

file.copy("home/document/folder_name/file_name.txt","home/document/folder_name2/file_name.txt")




To copy a file and replace a existing file with the same name:

file.copy("home/document/folder_name/file_name.txt","home/document/folder_name2/file_name.txt",overwrite=TRUE)


To copy multiple files from one directory to another:

file.copy(FILES,paste("home/document/folder_name2",FILES,sep="/"))



To change name of a file:

file.rename("home/document/folder_name/file_name.txt","home/document/folder_name/file_name2.txt")


To append files:

file.append("home/document/folder_name/file_name1.txt","home/document/folder_name/file_name2.txt","home/document/folder_name/file_name3.txt")

To compress a file into zip file:

zip("home/document/folder_name/zip_file_name.zip","home/document/folder_name/file_name.txt")



To extract files from compressed zip files:

unzip("home/document/folder_name/zip_file_name.zip",exdir="home/document/folder_name2")



To extract files from tar archive:

untar("home/document/folder_name/tar_file_name.tar",exdir="home/document/folder_name2")



To import gz files into R:
 

dat <- read.table(gzfile("path/file/txt.gz"), sep=", ", header = TRUE)  

  
  







Monday, 15 December 2014

boxplot & bwplot


'boxplot' is perhaps thought of as another way of representing 'densityplot' or distribution of the data. Hence, it is useful for comparing data by groups or categories within the data.

It works well with large dataset, compared to scatter plots which struggles when there are too many data points to plot.

The graphic parameters used for boxplot() are similar to plot().

Example:

boxplot(count~spray,InsectSprays)


























The above example show outliers. To remove these outliers from the graph, set 'outline' to FALSE.

boxplot(count~spray,InsectSprays,outline=FALSE)




























'bwplot' is 'lattice' package's version of boxplot, and the graphic parameters used for boxplot() are similar to xyplot().


Example:


bwplot(uptake~Type,CO2)




To remove outliers, set do.out=FALSE.

bwplot(uptake~Type,CO2,do.out=FALSE)



























With split panels,

bwplot(uptake~Treatment|Type,CO2)























To change colour of the median point

bwplot(uptake~Treatment|Type,CO2,col="red")






















To change colour of the median point and rectangle frame,

bwplot(uptake~Treatment|Type,CO2,col="red",
par.settings=list(box.rectangle=list(col="salmon",alpha=0.4)))























To change colour of the median point, rectangle frame and rectangle body,

bwplot(uptake~Treatment|Type,CO2,col="red",
par.settings=list(box.rectangle=list(col="salmon",fill="salmon",alpha=0.4)))























To change colour of the median point, rectangle frame, rectangle body and umbrella,


bwplot(uptake~Treatment|Type,CO2,col="red",
par.settings=list(box.rectangle=list(col="salmon",fill="salmon",alpha=0.4),box.umbrella=list(col="salmon",alpha=0.4)))





















To change colour of the median point, rectangle frame, rectangle body, umbrella and outlier,


bwplot(uptake~Treatment|Type,CO2,col="red",
par.settings=list(box.rectangle=list(col="salmon",fill="salmon",alpha=0.4),box.umbrella=list(col="salmon",alpha=0.4),plot.symbol=list(col="salmon",alpha=0.4)))























To overlap two bwplots for comparison,


bwplot(Sepal.Length~Species,iris,col="red",scale=list(y=list(lim=c(0,10))),key=list(space="top",column=2,text=list(label=c("Sepal Length","Petal Length"),cex=0.8,col="darkgrey"),
rectangles=list(col=c("salmon","dodgerblue"),rectangles=c("salmon","dodgerblue"),alpha=0.4,size=3)),
par.settings=list(box.rectangle=list(col="salmon",fill="salmon",alpha=0.4),box.umbrella=list(col="salmon",alpha=0.4),plot.symbol=list(col="salmon",alpha=0.4)))+
as.layer(bwplot(Petal.Length~Species,iris,col="blue",
par.settings=list(box.rectangle=list(col="dodgerblue",fill="dodgerblue",alpha=0.4),box.umbrella=list(col="dodgerblue",alpha=0.4),plot.symbol=list(col="dodgerblue",alpha=0.4)))
)








Blank Plots & Graphic Devices

To create blank plots, there are few options:

from 'base' package:

plot.new()

frame()

plot(1,type="n",axes=FALSE,xlab="",ylab="")



blank plots without margins

par(mar=rep(0,4)) 
plot(1,type="n",axes=FALSE,xlab="",ylab="")



using 'lattice' package:

xyplot(1~1,col="transparent",scales=list(draw=FALSE),xlab="",ylab="",par.settings=list(axis.line=list(col=0)))


To open graphic device:

x11()       #for linux, but also works for other OS if installed  

windows()     #for windows  

quartz()      #for Mac 

Friday, 17 October 2014

Regular Expression

Regular expression can be used in R to substitute, extract or search of pattern of texts.


To extract a part of texts, we can use sub() with "\\n" as the replacement (n is an integer, usually 1 or 2). The example extracts date from a file name "ABC_2014_10_23.csv".

sub("^[A-Za-z]+(_)([0-9]{4}(_)[0-9]{2}(_)[0-9]{2})(.)[A-Za-z]+","\\2","ABC_2014_10_23.csv")

"2014_10_23"


To replace certain words with another| word, we can do the following.

gsub("\\s*\\b(meters|m|meter)\\b","m",
"DAS FE TDAS 5meter ADSA RE 12 meters SA 23 Meters DASD 3 m",
ignore.case=TRUE)

"DAS FE TDAS 5meter ADSA RE 12m SA 23m DASD 3m"


To find fields matching the pattern, we can use grep().

The below looks for numbers followed by alphabet:

A<-c("SDA09DA","ADCZFD","081382","ASDF8673")
A[grep("[A-Z]+[0-9]+",A)]

"SDA09DA"  "ASDF8673"


The below looks for numbers between alphabets:

A<-c("SDA09DA","ADCZFD","081382","ASDF8673")
A[grep("[A-Z]+[0-9]+[A-Z]",A)]

"SDA09DA"


The below looks for more complex pattern. This example looks for typical address format.

A<-c("100 ASD ST DASER","CSADAS SS ASD ADA",
"321 DSA XCSACXZ SADAS 213","321/32 ASA ASDDD RD WEASF",
"DSA 231 DDG BGBVCVB","SUITE 1/43 SAFDSA AVE ASDA",
"UNIT 21/2 ADSD AV SDADFF")

A[grep("^[A-Z]*\\s*[0-9]+\\s*(/)*\\s*[0-9]*\\s*[A-Z]+\\s*[A-Z]*\\s*(ST|RD|AVE|AV)\\s*[A-Z]*$",A)]

"100 ASD ST DASER"           
"321/32 ASA ASDDD RD WEASF" 
"SUITE 1/43 SAFDSA AVE ASDA" 
"UNIT 21/2 ADSD AV SDADFF"  



For more regular expression language, go to either of the following websites:


http://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx

http://www.rexegg.com/regex-quickstart.html











Functions for Arithmatic

The following are some of the useful functions of arithmatic in R apart from +, -, *, /, ^ and sqrt()


To set limits before using scientific notation for large numbers, you can set the 'scipen' parameter within options(). The default limit is 10^12 for displaying in R console and 10^7 for the graphic device.

The below is larger than 10^13, and R reverts to using scientific notation.

31423190532586

3.142319e+13


By setting the option to scipen=15, the same number is retained in its natural form.

options(scipen=15)
31423190532586

31423190532586


For plotting:

plot(1:10,seq(0,100000000,length=10))
 


















options(scipen=8)
plot(1:10,seq(0,100000000,length=10))




















To round the figure to significant figures, you can use the below function.

signif(12645.654,digits=2)

13000


signif(0.00034526,digits=2)

0.00035



For rounding figures, you can do the following.

round(12645.654)  #rounds to integer

12646


round(12645.654,digits=2) #rounds to second decimal place

12645.65


round(0.00034526,digits=5)

0.00035



To find ceiling (smallest integer large than the given number) of a figure, you can do the following.

ceiling(12645.654)  

12646


ceiling(0.00034526)  

1


To find ceiling (largest integer smaller than the given number) of a figure, you can do the following.

floor(12645.654)

12645


floor(0.00034526)  

0



To find absolute figure, you can do the following.

abs(-243)

243


To find the remainder of a division, you can use '%%', but this does not work well with large numbers

15%%2

1


To find quotient of a division (integer part of division output), you can use '%/%'.

15%/%2

7