Archive for the ‘ R ’ Category

If you are using Ubuntu/Linux, you can install 
libcurl4-gnutls-dev and problem solved!
In your shell:
sudo apt-get install libcurl4-openssl-dev
sudo apt-get install libssl-dev
sudo apt-get install libcurl4-gnutls-dev
sudo apt-get install libxml2-dev

R online!

Todo mundo sabe da importância das linguagens de programação no mundo moderno e mais ainda para análise das dados. R é um ambiente computacional e uma linguagem de programação cuja popularidade cresce rapidamente. A linguagem é ótima para o tratamento, análise e visualização gráfica de dados. Hoje é considerado o melhor ambiente computacional para essa finalidade.

Existem milhares de sites que disponibilizam material para aprender a programar no R (https://blog.ufes.br/fabiomolinares/2017/04/26/free-100-online-tutorials-for-r-programming-statistics-and-graphics/). Mas, o acesso online pode facilitar a vida de um iniciante quando tenta usá-lo num equipamento que não o tenha  instalado ou ainda está no celular e quer fazer uso rápido do R.

Vou listar algumas alternativas que já usei:

  1. https://rnotebook.io/ (Roda Jupyter R notebooks online)
  2. http://www.r-fiddle.org/ (or https://cdn.datacamp.com/dcl-react-prod/example.html)
  3. https://repl.it/languages/rlang
  4. https://www.jdoodle.com/execute-r-online
  5. https://www.tutorialspoint.com/execute_r_online.php
  6. https://rweb.stat.umn.edu/Rweb/Rweb.general.html
  7. https://rdrr.io/snippets/
  8. https://rextester.com/l/r_online_compiler

Here is a list of FREE R tutorials hosted in official website of universities around the world. The tutorials are listed  in no particular order, actually based on when I have discovered it. They will be categorised soon. Please kindly suggest me other university-hosted online R tutorials by email to me@pairach.com.

A list of R tutorials, which are not hosted in the webpages of academic institutes can be found here.

  1. University of Oxford
     Modern Applied Statistics with S, 4edn (On-line material)[url]
    by  W. N. Venables and B. D. Ripley
  2. University of California at Davis
    Getting Started with the R Data Analysis Package [url]
    by Norm Matloff
  3. Clarkson University
    R Tutorial [url]
    by Kelly Black
  4. York University
    Getting started with R [url]
  5. University of Waterloo
    R Tutorial For  Windows and  Unix Environment [url]
  6. University of California at Los Angles, UCLA
    Resources to help you learn and use R [url]
  7. University of California at Riverside
    Programming in R [url]
  8. University of Illinois
    A Brief Introduction to R [url]
  9. University of Texas at Austin
    R Tutorial Videos [url]
    by Brandon K. Vaughn
  10. University of California at Berkeley
    An Introduction to R (pdf)
    by Phil Spector
  11. Chiang Mai University
    Econometrics with R (in Thai) [url]
    by Pairach Piboonrungroj
  12. University of California at Santa Babara
    R Programming Resource Centre [url]
    by National Center for Ecological Analysis and Synthesis
  13. University of Carnegie Mellon
    A Tutorial: Some Fundamentals of R [url]
    by Bruce E. Trumbo
  14. University of Illinois State
    R Tutorial [url]
    by Dong-Yun Kim
  15. University of MacMaster
    Introduction to the R Statistical Computing Environment [url]
    by John Fox.
  16. University of Princeton
    Introducing R [url]
    by Germán Rodríguez
  17. University of Amsterdam
    How to draw graphs with R (Graphics) [url]
    by Angelos-Miltiadis Krypotos
  18. University of North Texas
    Do it yourself – Introduction to R (Intro) [url]
  19. University of Warwick
    R programming page [url]
    (Biosciences: Molecular Organisation and Assembly in Cells)
    by Peter Cock.
  20. University of Illinois at Urbana-Champaign
    R tutorial for Applied Econometrics [url]
    by Prof. Roger Koenker
  21. Coastal Carolina University
    R tutorials (General) [url]
    by  William B. King
  22. University of Colorado Denver
    R Tutorial (General)[url]
    by  Stephanie Santorico and Mark Shin
  23. Stanford School of Medicine (Biomedical Informatics)
    R Tutorial (VDO on Introduction + Translational Bioinformatics (url)
  24. Harding University
    Producing Simple Graphs with R (basic graphic e.g., line, bar, hist, line) (url)
    by Frank McCown
  25. University of Kentucky, Department of Statistics
    Use Software R to do Survival Analysis and Simulation [pdf]
    by Mai Zhou
  26. University of Pittsburgh, Department of Statistics
    Time Series Analysis and Its Applications: With R Examples[url]
    by R.H. Shumway & D.S. Stoffer
  27. University of Toronto
    R Tutorial (for Ecology) [url]
    by the Cadotte Lab
  28. Florida State University
    Use R for Climate research [url]
    by James B. Elsner & Thomas H. Jagger
  29. University of Washington
    Introduction to R [url]
    by  Jinyoung Kim
  30. Lancaster University (UK)
    R tutorial [url]
    by  Joe Whittaker
  31. University of Georgia Athens
    A short R tutorial [pdf]
    by Steven M. Holland
  32. University of Twente
    R tutorials [url]
    (more than 1o tutorials about R in pdf + data & code)
    by D G Rossiter
  33. Vrijie University Amsterdam, Netherlands
    Handleiding R (in Dutch) [pdf]
    by A.W. van der Vaart
  34. University of Wisconsin-Madison
    Introduction to R [url]
    by Karl W Broman
  35. City University of New York
    simpleR Using R for Introductory Statistics [url]
    by  John Verzani
  36. Pomona College
    An R tutorial [pdf]
    by Jo Hardin
  37. University of Alaska Fairbanks 
    Using R [url]
    by the Biology & Wildlife Department computer
  38. University of Bath
    Practical Regression and Anova using R [pdf]
    Julian J. Faraway
  39. University of Goettingen
    Time Series Analysis with R – Part I [pdf]
    by Walter Zucchini and Oleg Nenadíc
    Statistical Analysis with R – a quick start – [pdf]
    by  Oleg Nenadíc and Walter Zucchini
  40. University of Washington, Department of Economics
    Working with Time Series Data in R [pdf]
    by Eric Zivot
  41. University of Liège, Faculty of Engineering
    Using R for Linear regression [pdf, 9 pages]
    by Kristel Van Steen
  42. University of Cambridge
    Local tips for R [url]  – in both statistics & graphics
    by Rudolf Cardinal
  43. Montana State University, Department of Mathematical Sciences
    Introduction to Sweave (R+LaTeX) [url]
    by Jim Robison-Cox
  44. Stanford University
    Social Network Analysis in R [url] including source R files and outputs
    by  McFarland, Daniel A., Solomon Messing, Michael Nowak and Sean J. Westwood.
  45. Ludwig-Maximilians-University Munich (Germany)
    Sweave (R + LaTeX) [url] including manuals and example files
    by Friedrich Leisch
  46. Ecole Polytechnique Fédérale de Lausanne
    Sweave = R • LaTeX^2 (pdf, slides)
    by Nicola Sartori
  47. University of Auckland
    Four course on Statistical Computing and Graphics including document, R codes (pdf)
    by Ross Ihaka
  48. Nova Southeastern University
    Many R tutorials using Tegrity-based video tutorials (url)
    by  Thomas W. MacFarland
  49. Penn State University
    – Introduction to R (get started) [url]
    – Welcome to STAT 497C – Topics in R Statistical Language! [url]
  50. Carnegie Mellon University
    Open & Free Course on Statistics (with applications in R among other software) [url]
  51. Centre for Mathematical Sciences, Lund University
    Exception handling in R [url]
    Object-oriented programming with references using S3/UseMethod [url]
    by Henrik Bengtsson
  52. University of Edinburgh
    Data Mining and Exploration (with examples with R) [url]
    by  Charles Sutton
  53. University of Washington
    Survey analysis in R [url]
    by Thomas Lumley
  54. Department of Psychology, University of Pennsylvania
    Notes on the use of R for psychology experiments and questionnaires [url]
    by Jonathan Baron and Yuelin Li
  55. College of Staten Island, Department of Mathematics
    simpleR: Using R for Introductory Statistics [url]
    By John Verzani
  56. Vanderbilt University
    rApache Manual [url]
  57. University of Aarhus, Department of Computer Science – Daimi, Faculty of Science
    RPy — R from Python [url]
  58. University of Auckland
    Many documents and links about R [url]
    By Paul  Murrell
  59. National Institute of Genetics (Japan)
    R Graphical Manual [url]
    By Osamu Ogasawara and IMS Lab Inc. Japan
  60. Montana State University
    R Labs for Vegetation Ecologists [url]
  61. University of Auckland
    Introduction to Data Technologies: Basic introduction to a number of computer technologies for working with data (HTML, XML, Databases, SQL, regular expressions, and R) [url]
    by Paul  Murrell
  62. Department of Statistics and Actuarial Science, SFU
    Technical Notes on the R programming language [url]
    by Sigal Blay
  63. University of Vienna
    Stattconn Project [url]
    by Thomas Baier and Erich Neuwirth
  64. Gunma University (Japan)
    R による統計処理  [url]
    by Shigenobu AOKI
  65. Tsukuba Office, Agriculture, Forestry and Fisheries Research Council Secretariat
    R Tips (in Japancese) [url]
  66. University of Western Ontario, Department of Statistical & Actuarial Sciences
    Debugging in R [url]
    by Duncan Murdoch
  67. University of Sunderland
    Programming in R [url]
    by Harry Erwin
  68. Smith College, Department of Mathematics and Statistics
    Use of R as a toolbox for mathematical statistics exploration [url]
    by Nicholas J. HortonElizabeth R.Brown and Linjuan Qian
  69. Katholieke Universiteit Leuven 
    R and Statistics [url]
    by Guido Wyseure
  70. Iowa State University
    Introduction to R [url]
    by Di Cook
  71. Cambridge University
    Graph redesign in R [url]
    by Stephen J. Murdoch
  72. Trinity College Dublin
    R Podcasts [url]
    by Andrew Jackson
  73. University of Arizona
    Introduction to R [url]
    by Caroline R.H. Wiley
  74. Cambridge University
    ESS: Emacs Speak Statistics [url]
    by Stephen Eglen
  75. Columbia University
    Running WinBugs and OpenBugs from R [url]
    Andrew Gelman
  76. University of Bremen
    vim R plugin for Linux/Unix [url]
    Johannes Ranke
  77. Montana State University
    R Web: Statistical Analysis on the web. [url]
    by Jeff Banfield
  78. University of Florida
    R for Categorical data analysis [html]
    by  Brett D. Presnell
  79. University of Auckland 
    An S (and R) Programming Workshop in 2003 (including slides, data and codes) [html]
    by The Quartet (affiliations at that moment)
    (1) Bill Venables (CSIRO, Australia)
    (2) Robert Gentleman (Harvard University)
    (3) Ross Ihaka (University of Auckland)
    (4) Paul Murrell (University of Auckland)
  80. Australian National University , Mathematical Science Institute
    Data Analysis and Graphics Using R – An Example-Based Approach [url]
    by John Maindonald and John Braun
  81. The Hebrew University
    Introduction to Statistical Thinking (With R, Without Calculus) [pdf]
    by Benjamin Yakir
  82. Basel Institute for Clinical Epidemiology and Biostatistics
    Tutorial: ggplot2 [pdf, 14 p.]
    by Ramon Saccilotto, Universitätsspital Basel
  83. UC, Davis: Bioinformatics
    Data Analysis and Visualization Course, 2012 (links to many sessions during two days of the course)
    by  Vince Buffalo, Joe Fass, Jie Peng and Dawei Lin
  84. University of Warwick
    R useR! Conference 2011 (links to materials and documents of the tutorials, invited talks and presentations)
    by  Department of Statistics, University of Warwick
  85. Vanderbilt University 
    R useR! Conference 2012 (links to materials and documents of short courses, tutorials, invited talks and presentations)
    by Department of Statistics, Vanderbilt University
  86. Technische Universität Wien, Vienna, Austria 
    useR! 2004: The 5th International R useRs Conference (links to materials of the conference)
    DSC 1999: The 1st conference for the developers of statistical software and researchers in statistical computing
    DSC 2001: The 2nd conference for the developers of statistical software and researchers in statistical computing
    DSC 2003: The 3rd conference for the developers of statistical software and researchers in statistical computing
    by  Department of Statistics and Probability Theory,Technische Universität Wien
  87. The University of Auckland
    DSC 2007: The 5th conference for the developers of statistical software and researchers in statistical computing
    (Workshops, Program, papers and posters)
    by Department of Statistics, The University of Auckland
  88. University of Oxford
    APTS Computer-Intensive Statistics 2012 (html) – Lecture note, datasets and codes
    by Prof. Brain Ripley
  89. Simon Fraser University
    Technical Notes on the R programming language
    by Sigal Blay
  90. University of Florida
    Introducing Monte Carlo Methods with R (pdf)
    by Christian P. Robert George Casella
  91. University of Tennessee
    pbdR — Programming with Big Data in R (html)
    Remote Data Analysis and Visulization Center
  92. National Center for Ecological Analysis and Synthesis
    The Regents of the University of California
    Integrate C Language Functions into R With an R Package
    – R: A self-learn tutorial
  93. Ghent University
    Teaching materials (slides, codes and datasets) for using lavaan package for Structural Equation Modeling (link)
    by Yves Rosseel
  94. Calvin College
    Computational Statistics Using R and R Studio – An Introduction for Scientists (pdf)
    by Randall Pruim
  95. Department of Mathematical Sciences
    Aalborg University, Denmark
    Graphical Models with R (pdf)
    Soren Hojsgaard
  96. Statistics Department
    Carnegie Mellon University
    Writing R Functions (pdf)
    by Cosma Shalizi
  97. Institute for Environmental Sciences
    University Koblenz-Landau
    Lecture “Applied Multivariate Statistics” 2011/2012 (url)
    by Ralf Schäfer
  98. University of Groningen, The Netherlands
    R Tutorial for Applied Statistics (URL)
    by Anne Boomsma
  99. University of Florida
    Tutorial on Making Simple R Packages (URL)
  100. University of Göttingen – Georg-August-Universität Göttingen
    Time Series Analysis with R – Part I (PDF)
    by Walter Zucchini, Oleg Nenadi´c
  101. Harvard University
    Quick Introduction to Graphics in R Introduction to the R language (pdf)
    by Aedin Culhane
  102. University of Pennsylvania
    R Study Group (General guide to R) (URL)
    Josef Fruehwald

You want to use the devtools package. Suposse that you have run the following commands:

> install.packages("devtools", dependencies = TRUE)
...
> library(devtools)
Error in library(devtools) : there is no package 
called ‘devtools’

The 'devtools' package was not installed!


Solution: I installed libcurl4-gnutls-dev and the 
problem was solved.

In your shell:

apt-get -y build-dep libcurl4-gnutls-dev
apt-get -y install libcurl4-gnutls-dev

How to update R software in windows?

Nowadaysthe R software update on Windows is not more a boring task. The R can be easily updated with the “installr” package. Just follow these steps:
  1. Install the package using install.packages(“installr”)
  2. Load package with library(“installr”)
  3. Use the function updateR() to update!

The dialog box will be opened to take you through the following steps:
  1. It checks for a newer version of R.
  2. If one exists, the function will download the most updated R version and run its installer.
  3. Once done, the function will offer to copy (or move) all of the packages from the old R library to the new R library.
  4. It will then offer to update the moved packages, offer to open the new Rgui, and lastely, it will quit the old R.

A sphere in R using rgl package

The rgl.spheres function is a fantastic way to plot spheres! Look at!

library("rgl")

rgl.spheres(1,1,1,radius=1,color="blue")

YES! yes, it’s very simple. I will describe the procedure:

1. You should create the file with code R. Command-line parameters are accessible via commandArgs().

2. You can use Rscript on all platforms, including Windows. It will support commandArgs(), for example: In the terminal

Rscript myscript.R arg1 arg2 arg3

arg1, arg2 and arg3 are arguments into your R script. If your args are strings with spaces in them, enclose within double quotes. There are two add-on packages on CRAN — getopt and optparse — which were both written for command-line parsing.

Tiny example: script.R

options(echo=TRUE) # To see commands in output file
args <- commandArgs(trailingOnly = TRUE) 
# trailingOnly=TRUE means that only your 
# arguments are returned
print(args) 

start_date <- as.Date(args[1]) # First argument
figure_name <- args[2] # Second argument
n <- as.integer(args[3]) # Third argument
rm(args)

# Some computations:
x <- rnorm(n)
postscript(paste(figure_name,".eps",sep=""))
plot(start_date+(1L:n), x,type="l")
dev.off()

summary(x)

To run:

Rscript script.R 02/06/2015 figure 1000

Booktabs package and Sweave

The booktabs package in latex makes really beautiful tables. This package provide some additional commands to enhance the quality of table in LaTeX, especially if there is math in your table that might run up against the regular \hline in the tabular environment. I created a table with the following code:

% file: example.Rnw
% require xtable
\documentclass{article}
\usepackage{booktabs}

\begin{document}

\begin{table}[!h] 
\centering
\caption{This is my table.}
\label{tab:table1}
<<mytable,echo=F,results=tex>>=
mat <- as.data.frame(matrix(runif(25),nrow=5))
colnames(mat) <- c("$\\alpha$","$\\beta$",
"$\\gamma$","$\\delta$","$\\frac{\\epsilon}{2}$")
rownames(mat) <- c(‘A’,’B’,’C’,’D’,’E’)
mat <- xtable::xtable(mat,digits=rep(5,ncol(mat)+1))
print(mat, 
sanitize.text.function = 
    function(x){x},
        floating=FALSE, 
        hline.after=NULL, 
        add.to.row=list(pos=list(-1,0,
        nrow(mat)), command=c('\\toprule\n',
        '\\midrule\n','\\bottomrule\n')))
@
\end{table}
\end{document}

 

You can use to compile:

$ R CMD Sweave example.Rnw
$ pdflatex example.tex

The definition of \toprule\midrule and \bottomrule from
booktabs package is:

\def\toprule{\noalign{\ifnum0=`}\fi
  \@aboverulesep=\abovetopsep
  \global\@belowrulesep=\belowrulesep 
  \global\@thisruleclass=\@ne
  \@ifnextchar[{\@BTrule}{\@BTrule[\heavyrulewidth]}}
\def\midrule{\noalign{\ifnum0=`}\fi
  \@aboverulesep=\aboverulesep
  \global\@belowrulesep=\belowrulesep
  \global\@thisruleclass=\@ne
  \@ifnextchar[{\@BTrule}{\@BTrule[\lightrulewidth]}}
\def\bottomrule{\noalign{\ifnum0=`}\fi
  \@aboverulesep=\aboverulesep
  \global\@belowrulesep=\belowbottomsep
  \global\@thisruleclass=\@ne
  \@ifnextchar[{\@BTrule}{\@BTrule[\heavyrulewidth]}}
set.seed(34567)
x <- runif(10); y <- 4*x+rnorm(10) 
fit <- lm(y~x)
r2 <- summary(fit)$r.squared

# plot data and regression line
plot(x, y)
abline(fit, col=2)

# add text to plot with legend()
legend('topleft', title='option 1', 
legend=sprintf("y = %3.2fx %+3.2f, R\UB2 = %3.2f", 
coef(fit)[2],coef(fit)[1], r2), bty='n', cex=0.7) 

# if you prefer a space between plus/minus and b
b<-coef(fit)[1]
if(b<0) {b_sign='-'; b=-b} else {b_sign= '+'}
 
legend('topright', title='option 2', 
legend=sprintf("y = %3.2f x %s %3.2f, R\UB2 = %3.2f", 
coef(fit)[2],b_sign,b,r2), bty='n',cex=0.7)

Important: R\UB2B2 defined R square symbol. B2 is the hex code for UTF-8 character ² and \U is a control sequence that will call that character.

 
regression1

Decimal places in R plot legend?

For specifying the number of digits, tipically we use the command round, for example:

round(pi, digits=2)

[1] 3.14

However, we can also use sprintf  command to deal with both the number of digits and the + or – in your equation, for example:

sprinf(“%3.2f”,pi)

[1] “3.14”

Note that, 3.2f controls the number of digits and the symbol forces the + or sign in a equation.