Monday, May 14, 2012

R

1. Ubuntu
sudo apt-get install r-base r-base-html r-doc-html

2. getting help on a function
help(mean)
?mean
example(mean)

3. getting and setting the working directory
 getwd()
 setwd()

4. Accessing the functions in a package
library(packageName)

5. Accessing built-in datasets
data(dsname, package="pkname")

6.installing packages from CRAN
install.packages("packagename")

7. running a script
source("myScript.R")

8. Running a batch script
R CMD BATCH scriptfile outputfile

--slave, inhibiting echo of the input

Rscript myScript.R arg1 arg2 arg3

9. loading packages
require(tseries)

10. redirecting output to a file
cat("The answer is", answer, "\n", file="filename")

cat(data,file="filename", append=TRUE)

sink("filename") # begin writing output to file

....

sink() # resume writing output to console

11. reading fixed-width records
read.fwf("filename", widths=c(w1,w2,...wn))

12. reading tabular data files (white space)
read.table("filename")

13. reading from csv files
read.csv("filename")

14. writing to csv files
write.csv(x,"filename", row.names=FALSE)

15. Selecting data frame columns by name
dfrm[["name"]]
dfrm$name

16. selecting rows and columns
select columns
subset(dfrm, select=colname)
subset(dfrm, select=c(colname1, colname2, ... colnamen))

select rows
subset(dfrm, subset=(colname > 0))
subset(dfrm, select=c(predictor, response),subset=(response > 0))

17. removing NAs from a data frame
clean <- na.omit(dfrm)

18. excluding columns by name
subset(dfrm, select=-badboy) # all columns except badboy

19. merge data frames by common column
m <- merge(df1, df2, by="name")

20. accessing data frame contents more easily
attach(dataframe)

21. converting one atomic value to another
as.character(x)
as.complex(x)
as.numeric(x)
as.double(x)
as.integer(x)
as.logical(x)

22.