Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

March 22, 2019

Quickly Install R on Ubuntu 17.10

October 19, 2017
By Mauricio Vargas S. 帕夏

This script will install everything.

# Install R
sudo apt-get update
sudo apt-get install gdebi libxml2-dev libssl-dev libcurl4-openssl-dev libopenblas-dev r-base r-base-dev

# Install RStudio
cd ~/Downloads
wget https://download1.rstudio.org/rstudio-xenial-1.1.383-amd64.deb
sudo gdebi rstudio-xenial-1.1.383-amd64.deb
printf '\nexport QT_STYLE_OVERRIDE=gtk\n' | sudo tee -a ~/.profile

# install common packages
R --vanilla << EOF install.packages(c("tidyverse","data.table","dtplyr","devtools","roxygen2","bit64"), repos = "https://cran.rstudio.com/") q() EOF # Export to HTML/Excel R --vanilla << EOF install.packages(c("htmlTable","openxlsx"), repos = "https://cran.rstudio.com/") q() EOF # Blog tools R --vanilla << EOF install.packages(c("knitr","rmarkdown"), repos='http://cran.us.r-project.org') q() EOF sudo apt-get install python-pip sudo pip install markdown rpy2==2.7.8 pelican==3.6.3 # PDF extraction tools sudo apt-get install libpoppler-cpp-dev default-jre default-jdk r-cran-rjava sudo R CMD javareconf R --vanilla << EOF library(devtools) install.packages("pdftools", repos = "https://cran.rstudio.com/") install_github("ropensci/tabulizer") q() EOF # TTF/OTF fonts usage sudo apt-get install libfreetype6-dev R --vanilla << EOF install.packages("showtext", repos = "https://cran.rstudio.com/") q() EOF # Cairo for graphic devices sudo apt-get install libgtk2.0-dev libxt-dev libcairo2-dev R --vanilla << EOF install.packages("Cairo", repos = "https://cran.rstudio.com/") q() EOF
©

September 29, 2014

Drawing a 95% confidence interval in R

Posted on August 5, 2013 by Nathan Lemoine

I’m writing a post on how to draw a in 95% confidence interval in R by hand. I spent an hour or so trying to figure this out, and most message threads point someone to the ellipse() function. However, I wanted to know how it works.

The basic problem was this. Imagine two random variables with a bivariate normal distribution, called y, which is an x 2 matrix with n rows and 2 columns. The random variables are described by a mean vector mu and covariance matrix S. The equation for an ellipse is:

(y – mu) S^1 (y – mu)’ = c^2

The number c^2 controls the radius of the ellipse, which we want to extend to the 95% confidence interval, which is given by a chi-square distribution with 2 degrees of freedom. The ellipse has two axes, one for each variable. The axes have half lengths equal to the square-root of the eigenvalues, with the largest eigenvalue denoting the largest axis. A further description of this can be found in any multivariate statistics book (or online).

To calculate the ellipse, we need to do a few things: 1) convert the variables to polar coordinates, 2) extend the new polar variables by the appropriate half lengths (using eigenvalues), 3) rotate the coordinates based on the variances and covariances, and 4) move the location of the new coordinates back to the original means. This will make more sense when we do it by hand.

First, generate some data, plot it, and use the ellipse() function to make the 95% confidence interval. This is the target interval (I use it to check myself. If my calculations match, hooray. If not, I screwed up).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
library(mvtnorm) # References rmvnorm()
library(ellipse) # References ellipse()
set.seed(17)
 
# Set the covariance matrix
sigma2 <- matrix(c(5, 2, 2, 5), ncol=2)
 
# Set the means
mu <- c(5,5)
 
# Get the correlation matrix
P <- cov2cor(sigma2)
 
# Generate the data
p <- rmvnorm(n=50, mean=mu, sigma=sqrt(sigma2))
 
# Plot the data
plot(p)
 
# Plot the ellipse
lines( ellipse( P, centre = c(5,5)) , col='red')

Second, get the eigenvalues and eigenvectors of the correlation matrix.

1
2
evals <- eigen(P)$values
evecs <- eigen(P)$vectors

Third, make a vector of coordinates for a full circle, from 0 to 2*pi and get the critical value (c^2).

1
2
3
4
5
6
# Angles of a circle
a <- seq(0, 2*pi, len=100)
 
# Get critical value
c2 <- qchisq(0.95, 2)
c <- sqrt(c2)

The vector A above are angles that describe a unit circle. The coordinates of a unit circle are found by x = cos(a) and y = sin(a) (use trigonometry of a triangle to get this, where the hypotenuse = 1). We need to extend the unit circle by the appropriate lengths based on the eigenvalues and then even more by the critical value.

1
2
3
4
5
# Get the distances
xT <- c * sqrt(evals[1]) * cos(a)
yT <- c * sqrt(evals[2]) * sin(a)
 
M <- cbind(xT, yT)

If you plot M, you’ll get an ellipse of the appropriate axes lengths, but centered on 0 and unrotated. Rotate the ellipse using the eigenvectors, which describe the relationships between the variables (more appropriately, they give the directions for the vectors of the major axes of variation). Use the equation u*M’ (write this out to see why this works).

1
2
3
# Covert the coordinates
transM <- evecs %*% t(M)
transM <- t(transM)

The final step is to move the rotated ellipse back to the original scale (centered around the original means) and plot the data.

1
lines(transM + mu)

This gives the following plot, with the red line being the output from the ellipse() function.
And that’s that! Hopefully this helps someone like me who spent hours looking but couldn’t find anything.
©

September 23, 2014

Basic Probability Distributions in R

We look at some of the basic operations associated with probability distributions. There are a large number of probability distributions available, but we only look at a few. If you would like to know what distributions are available you can do a search using the command help.search(“distribution”).

Here we give details about the commands associated with the normal distribution and briefly mention the commands for other distributions. The functions for different distributions are very similar where the differences are noted below.

For this chapter it is assumed that you know how to enter data which is covered in the previous chapters.

To get a full list of the distributions available in R you can use the following command:
help(Distributions)

For every distribution there are four commands. The commands for each distribution are prepended with a letter to indicate the functionality:

“d” returns the height of the probability density function
“p” returns the cumulative density function
“q” returns the inverse cumulative density function (quantiles)
“r” returns randomly generated numbers

 

The Normal Distribution

There are four functions that can be used to generate the values associated with the normal distribution. You can get a full list of them and their options using the help command:
> help(Normal)
The first function we look at it is dnorm. Given a set of values it returns the height of the probability distribution at each point. If you only give the points it assumes you want to use a mean of zero and standard deviation of one. There are options to use different values for the mean and standard deviation, though:

> dnorm(0)
[1] 0.3989423
> dnorm(0)*sqrt(2*pi)
[1] 1
> dnorm(0,mean=4)
[1] 0.0001338302
> dnorm(0,mean=4,sd=10)
[1] 0.03682701
>v <- c(0,1,2)
> dnorm(v)
[1] 0.39894228 0.24197072 0.05399097
> x <- seq(-20,20,by=.1)
> y <- dnorm(x)
> plot(x,y)
> y <- dnorm(x,mean=2.5,sd=0.1)
> plot(x,y)
The second function we examine is pnorm. Given a number or a list it computes the probability that a normally distributed random number will be less than that number. This function also goes by the rather ominous title of the “Cumulative Distribution Function.” It accepts the same options as dnorm:
> pnorm(0)
[1] 0.5
> pnorm(1)
[1] 0.8413447
> pnorm(0,mean=2)
[1] 0.02275013
> pnorm(0,mean=2,sd=3)
[1] 0.2524925
> v <- c(0,1,2)
> pnorm(v)
[1] 0.5000000 0.8413447 0.9772499
> x <- seq(-20,20,by=.1)
> y <- pnorm(x)
> plot(x,y)
> y <- pnorm(x,mean=3,sd=4)
> plot(x,y)
If you wish to find the probability that a number is larger than the given number you can use the lower.tail option:
> pnorm(0,lower.tail=FALSE)
[1] 0.5
> pnorm(1,lower.tail=FALSE)
[1] 0.1586553
> pnorm(0,mean=2,lower.tail=FALSE)
[1] 0.9772499
The next function we look at is qnorm which is the inverse of pnorm. The idea behind qnorm is that you give it a probability, and it returns the number whose cumulative distribution matches the probability. For example, if you have a normally distributed random variable with mean zero and standard deviation one, then if you give the function a probability it returns the associated Z-score:
> qnorm(0.5)
[1] 0
> qnorm(0.5,mean=1)
[1] 1
> qnorm(0.5,mean=1,sd=2)
[1] 1
> qnorm(0.5,mean=2,sd=2)
[1] 2
> qnorm(0.5,mean=2,sd=4)
[1] 2
> qnorm(0.25,mean=2,sd=2)
[1] 0.6510205
> qnorm(0.333)
[1] -0.4316442
> qnorm(0.333,sd=3)
[1] -1.294933
> qnorm(0.75,mean=5,sd=2)
[1] 6.34898
> v = c(0.1,0.3,0.75)
> qnorm(v)
[1] -1.2815516 -0.5244005  0.6744898
> x <- seq(0,1,by=.05)
> y <- qnorm(x)
> plot(x,y)
> y <- qnorm(x,mean=3,sd=2)
> plot(x,y)
> y <- qnorm(x,mean=3,sd=0.1)
> plot(x,y)
The last function we examine is the rnorm function which can generate random numbers whose distribution is normal. The argument that you give it is the number of random numbers that you want, and it has optional arguments to specify the mean and standard deviation:

> rnorm(4)
[1]  1.2387271 -0.2323259 -1.2003081 -1.6718483
> rnorm(4,mean=3)
[1] 2.633080 3.617486 2.038861 2.601933
> rnorm(4,mean=3,sd=3)
[1] 4.580556 2.974903 4.756097 6.395894
> rnorm(4,mean=3,sd=3)
[1]  3.000852  3.714180 10.032021  3.295667
> y <- rnorm(200)
> hist(y)
> y <- rnorm(200,mean=-2)
> hist(y)
> y <- rnorm(200,mean=-2,sd=4)
> hist(y)
> qqnorm(y)
> qqline(y)

 

The Chi-Squared Distribution

There are four functions that can be used to generate the values associated with the Chi-Squared distribution. You can get a full list of them and their options using the help command:
> help(Chisquare)
These commands work just like the commands for the normal distribution. The first difference is that it is assumed that you have normalized the value so no mean can be specified. The other difference is that you have to specify the number of degrees of freedom. The commands follow the same kind of naming convention, and the names of the commands are dchisq, pchisq, qchisq, and rchisq.
A few examples are given below to show how to use the different commands. First we have the distribution function, dchisq:
> x <- seq(-20,20,by=.5)
> y <- dchisq(x,df=10)
> plot(x,y)
> y <- dchisq(x,df=12)
> plot(x,y)
Next we have the cumulative probability distribution function:
> pchisq(2,df=10)
[1] 0.003659847
> pchisq(3,df=10)
[1] 0.01857594
> 1-pchisq(3,df=10)
[1] 0.981424
> pchisq(3,df=20)
[1] 4.097501e-06
> x = c(2,4,5,6)
> pchisq(x,df=20)
[1] 1.114255e-07 4.649808e-05 2.773521e-04 1.102488e-03
Next we have the inverse cumulative probability distribution function:
> qchisq(0.05,df=10)
[1] 3.940299
> qchisq(0.95,df=10)
[1] 18.30704
> qchisq(0.05,df=20)
[1] 10.85081
> qchisq(0.95,df=20)
[1] 31.41043
> v <- c(0.005,.025,.05)
> qchisq(v,df=253)
[1] 198.8161 210.8355 217.1713
> qchisq(v,df=25)
[1] 10.51965 13.11972 14.61141
Finally random numbers can be generated according to the Chi-Squared distribution:
> rchisq(3,df=10)
[1] 16.80075 20.28412 12.39099
> rchisq(3,df=20)
[1] 17.838878  8.591936 17.486372
> rchisq(3,df=20)
[1] 11.19279 23.86907 24.81251

©

September 3, 2014

How to fit data that looks like a gaussian?

I am quite new to statistics, so please forgive me for using probably the wrong vocabulary.
I have some data that looks (to me) like a gaussian when plotted.
The data is an extract from a jpeg image. It's a vertical line taken from the image, and only the Red data is used (from RGB).
Here is the full data (27 data points):
> r
 [1] 0.003921569 0.031372549 0.023529412 0.015686275 0.003921569 0.027450980
 [7] 0.003921569 0.015686275 0.031372549 0.105882353 0.305882353 0.490196078
[13] 0.560784314 0.615686275 0.592156863 0.505882353 0.364705882 0.227450980
[19] 0.050980392 0.031372549 0.019607843 0.054901961 0.031372549 0.015686275
[25] 0.027450980 0.003921569 0.011764706

> dput(r)
c(0.00392156862745098, 0.0313725490196078, 0.0235294117647059, 
0.0156862745098039, 0.00392156862745098, 0.0274509803921569, 
0.00392156862745098, 0.0156862745098039, 0.0313725490196078, 
0.105882352941176, 0.305882352941176, 0.490196078431373, 0.56078431372549, 
0.615686274509804, 0.592156862745098, 0.505882352941176, 0.364705882352941, 
0.227450980392157, 0.0509803921568627, 0.0313725490196078, 0.0196078431372549, 
0.0549019607843137, 0.0313725490196078, 0.0156862745098039, 0.0274509803921569, 
0.00392156862745098, 0.0117647058823529)
plot(r)
 
-------------------
 
Fitting a distribution is, roughly speaking, what you'd do if you made a histogram of your data, and tried to see what sort of shape it had. What you're doing, instead, is simply plotting a curve. That curve happens to have a hump in the middle, like what you get by plotting a gaussian density function.
To get what you want, you can use something like optim to fit the curve to your data. The following code will use nonlinear least-squares to find the three parameters giving the best-fitting gaussian curve: m is the gaussian mean, s is the standard deviation, and k is an arbitrary scaling parameter (since the gaussian density is constrained to integrate to 1, whereas your data isn't).
x <- seq_along(r)

f <- function(par)
{
    m <- par[1]
    sd <- par[2]
    k <- par[3]
    rhat <- k * exp(-0.5 * ((x - m)/sd)^2)
    sum((r - rhat)^2)
}

optim(c(15, 2, 1), f, method="BFGS", control=list(reltol=1e-9))
 

I propose to use non-linear least squares for this analysis.
# First present the data in a data-frame
tab <- data.frame(x=seq_along(r), r=r)
#Apply function nls
(res <- nls( r ~ k*exp(-1/2*(x-mu)^2/sigma^2), start=c(mu=15,sigma=5,k=1) , data = tab))
And from the output, I was able to obtain the following fitted "Gaussian curve":
v <- summary(res)$parameters[,"Estimate"]
plot(r~x, data=tab)
plot(function(x) v[3]*exp(-1/2*(x-v[1])^2/v[2]^2),col=2,add=T,xlim=range(tab$x) )
©

R: Robust fitting of data points to a Gaussian function

Fitting a Gaussian curve to the data, the principle is to minimise the sum of squares difference between the fitted curve and the data, so we define f our objective function and run optim on it:
 
fitG =
function(x,y,mu,sig,scale){

  f = function(p){
    d = p[3]*dnorm(x,mean=p[1],sd=p[2])
    sum((d-y)^2)
  }

  optim(c(mu,sig,scale),f)
 }

Now, extend this to two Gaussians:
 
fit2G <- function(x,y,mu1,sig1,scale1,mu2,sig2,scale2,...){

  f = function(p){
    d = p[3]*dnorm(x,mean=p[1],sd=p[2]) + p[6]*dnorm(x,mean=p[4],sd=p[5])
    sum((d-y)^2)
  }
  optim(c(mu1,sig1,scale1,mu2,sig2,scale2),f,...)
}

Fit with initial params from the first fit, and an eyeballed guess of the second peak. Need to increase the max iterations:
 
> fit2P = fit2G(data$V3,data$V6,6,.6,.02,8.3,0.10,.002,control=list(maxit=10000))
Warning messages:
1: In dnorm(x, mean = p[1], sd = p[2]) : NaNs produced
2: In dnorm(x, mean = p[4], sd = p[5]) : NaNs produced
3: In dnorm(x, mean = p[4], sd = p[5]) : NaNs produced
> fit2P
$par
[1] 6.035610393 0.653149616 0.023744876 8.317215066 0.107767881 0.002055287

What does this all look like?
 
> plot(data$V3,data$V6)
> p = fit2P$par
> lines(data$V3,p[3]*dnorm(data$V3,p[1],p[2]))
> lines(data$V3,p[6]*dnorm(data$V3,p[4],p[5]),col=2)




However I would be wary about statistical inference about your function parameters...
The warning messages produced are probably due to the sd parameter going negative. You can fix this and also get a quicker convergence by using L-BFGS-B and setting a lower bound:
 
> fit2P = fit2G(data$V3,data$V6,6,.6,.02,8.3,0.10,.002,control=list(maxit=10000),method="L-BFGS-B",lower=c(0,0,0,0,0,0))
> fit2P
$par
[1] 6.03564202 0.65302676 0.02374196 8.31424025 0.11117534 0.00208724

As pointed out, sensitivity to initial values is always a problem with curve fitting things like this.

©

bash script, erase previous line?

Q: In lots of Linux programs, like curl, wget, and anything with a progress meter, they have the bottom line constantly update, every certain amount of time. How do I do that in a bash script?


A:

{
for pc in $(seq 1 100); do
echo -ne "$pc%\033[0K\r"
usleep 100000
done
echo
}

The "\033[0K" will delete to the end of the line - in case your progress line gets shorter at some point, although this may not be necessary for your purposes.

The "\r" will move the cursor to the beginning of the current line

The -n on echo will prevent the cursor advancing to the next line
©

September 2, 2014

Multivariate Computations

This tutorial deals with a few multivariate techniques including clustering and principal components. We begin with a short introduction to generating multivariate normal random vectors.

Multivariate normal distributions

We'll start off by generating some multivariate normal random vectors. There are packages that do this automatically, such as the mvtnorm package available from CRAN, but it is easy and instructive to do from first principles.

Let's generate from a bivariate normal distribution in which the standard deviations of the components are 2 and 3 where the correlation between the components is -1/2. For simplicity, let the mean of the vectors be the origin. We need to figure out what the covariance matrix looks like.

The diagonal elements of the covariance matrix are the marginal variances, namely 4 and 9. The off-diagonal element is the covariance, which equals the correlation times the product of the marginal standard deviations, or -3:
sigma <- matrix(c(4,-3,-3,9),2,2)
   sigma
We now seek to find a matrix M such that M times its transpose equals sigma. There are many matrices that do this; one of them is the transpose of the Cholesky square root:
M <- t(chol(sigma))
   M %*% t(M)
We now recall that if Z is a random vector and M is a matrix, then the covariance matrix of MZ equals M cov(Z) Mt. It is very easy to simulate normal random vectors whose covariance matrix is the identity matrix; this is accomplished whenever the vector components are independent standard normals. Thus, we obtain a multivariate normal random vector with covariance matrix sigma if we first generate a standard normal vector and then multiply by the matrix M above. Let us create a dataset with 200 such vectors:
Z <- matrix(rnorm(400),2,200) # 2 rows, 200 columns
   X <- t(M %*% Z)
The transpose above is taken so that X becomes a 200x2 matrix, since R prefers to have the columns as the vector components rather than the rows. Let us now plot the randomly generated normals and find the sample mean and covariance.
plot(X)
   Xbar <- apply(X,2,mean)
   S <- cov(X)
We can compare the S matrix with the sigma matrix, but it is also nice to plot an ellipse to see what shape these matrices correspond to. The car package, which we used in the EDA and regression tutorial, has the capability to plot ellipses. You might not need to run the install.packages function below since this package may already have been installed in the previous tutorial. However, the library function is necessary.
install.packages("car",lib="V:/")
   library(car,lib.loc="V:/")
To use the ellipse function in the car package, we need the center (mean), shape (covariance), and the radius. The radius is the radius of a circle that represents the "ellipse" for a standard bivariate normal distribution. To understand how to provide a radius, it is helpful to know that if we sum the squares of k independent standard normal random variables, the result is (by definition) a chi-squared random variable on k degrees of freedom. Thus, for a standard bivariate normal vector, the squares of the radii should be determined by the quantiles of the chi-squared distribution on 2 degrees of freedom. Let us then construct an ellipses with radius based on the median of the chi-squared distribution. Thus, this ellipse should contain roughly half of the points generated. We'll also produce a second ellipse, based on the true mean and covariance matrix, for purposes of comparison.
ellipse(Xbar, S, sqrt(qchisq(.5,2)))
   ellipse(c(0,0), sigma, 
      sqrt(qchisq(.5,2)), col=3, lty=2)
 
©

August 20, 2014

R: Getting started with R

Main page on R
Don't try to do too much in one session. You might like to just install R and then come back and do further steps such as going through the Venables and Ripley tutorial and installing libraries. Finally you will want to use project directories in which you keep data, scripts and other files pertaining to a particular project.
For a quick start, focus on the items that are marked QUICK START:.

Contents

[hide]

Installing R

Windows, Mac or Linux

QUICK START: To install R, you can go to the CRAN (Comprehensive R Archive Network website) and follow the instructions.
You should consider installing RStudio, a recently released IDE (Integrated Development Environment) for using R that has gained rapid popularity.
You will eventually need to install additional packages which you can do easily whenever your computer is connected to the internet.

Further information

You can get more information on installing R and RStudio at John Fox's website.

Starting to learn R: Tutorials on the Web

Start by working through sample scripts. This is probably the best way to start exploring and enjoying R without getting overwhelmed by long explanations.
After working though sample scripts, you can explore other tutorials:
  1. A list of tutorials recently (January 2012) recommended on the LinkedIn blog The R Project for Statistical Computing:
  2. An annotated list elsewhere on this wiki: R: R tutorials and courses.
  3. An extensive list of on-line books and tutorials is available from the CRAN site.
  4. Chris Green at the University of Washington has an excellent very accessible on-line book: Christopher Green: R Primer
  5. An introductory sample session: http://cran.r-project.org/doc/manuals/R-intro.html#A-sample-session
  6. The very basics from a tutorial at the University of Waterloo.
  7. The first chapter of Venables and Ripley adapted to R VR4: Chapter 1 summary. This is more of an introductory session than a tutorial. It gives a good overview of the potential in using R as well as introducing a number of interesting statistical ideas.
  8. The tutorial that comes with R[1] is extensive but gradually working through it might be the best way to become proficient.
  9. R tutorial at UCLA This is good but takes you through some things you won't really need.
  10. The start of a local tutorial (please contribute)
  11. If you are already familiar with SAS or SPSS you should have a look at Rob Munchen (2007) R for SAS and SPSS Users

Other interesting tutorials on the web

If you find other good tutorials, please add links, preferably with short comments, here
Short introduction to the basic features of R. A good point to start.
Introduction to R with a lot of statistical examples
  • An Introduction to R: Software for Statistical Modelling & Computing 3 by Petra Kuhnert and Bill Venables:
http://cran.r-project.org/doc/contrib/Kuhnert+Venables-R_Course_Notes.zip
Extensive non-technical coverage of R, 364 pages
Reference introductory text for using R.

Script Editors

The built-in editor lacks some desirable features. For example, under Windows, it does not show matching parentheses. You will probably want to get a separate editor.
Recently released RStudio, which is free, provides an integrated environment including a script editor that will probably displace previously available editors.
RStudio has probably superseded previous R editors but for historical completeness one can metion a number of other possibilities, some of which are free. Emacs is very powerful but difficult to learn, Tinn-R (see below) under Windows is easier to install and use but suffers from less than perfect reliability. WinEdt is not expensive (Academic: US$40) and is considered a very good editor with an interface, R-WinEdt designed for R.

Keeping your work

Probably, the ideal way (as of the fall of 2013) to keep output and to perform analyses in a way that is reproducible is to use R Markdown in RStudio.
A more primitive but simple way to keep output and selected graphs so they can eventually become part of a report is to copy and paste output and graphs into a Word file. Graphs can be copied and pasted as 'Windows metafiles' without loss of resolution. Text in the R output window should be pasted with a 'fixed width font' such as Courier New.

Using and installing packages

Many packages come with R. To use them in an R session, you need to load the package. For example to load the MASS package which contains functions and datasets that accompany Venables and Ripley, Modern Applied Statistics with S, you use the command:
> library(MASS)
To get an overview of what's available in MASS, you use:
> library(help=MASS)

Installing additional packages

Some packages are not automatically installed when you install R but they need to be downloaded and installed individually. An important example is the 'car' package that accompanies Fox, Applied Regression. You install it with the R command:
> install.packages("car")
After installing it you load it the same way as a pre-installed package, i.e.
> library(car)
To get information about the package, use:
> library(help = car)
On your own computer, the package needs to be installed only once. On a lab computer you may need to reinstall in each new session.
At this stage, have a look at R basics on the UCLA ATS web site.

Setting up project directories

RStudio provides facilities for managing project directories. If you are working only with R you can organize your work in project directories as follows:
  • Create a directory for your project.
  • Copy a workspace (a .Rdata file) to the directory
  • You can then start R by clicking on the .Rdata file's icon
  • All directory references in the R session will be relative to the project directory. For example, you can read a file 'data.csv' in the directory with
> data <- read.csv('data.csv')

R lessons

Template:Incomplete
Generate links to a set of lessons people can use to learn R. Each lesson should take approximately 1 hour and contain exercises.

R Tip sheets

Exploring more deeply

Exploring much more deeply

This is not up to date. Please help
  • R Portal at UCLA[4]

Courses in specialized areas

Later

Incomplete

Introductions to R

Materials from John Fox

Materials from John Fox

Use stuff from here: Getting Started page on the old math wiki
©

Getting Started with the R Data Analysis Package

Professor Norm Matloff
Dept. of Computer Science
University of California at Davis
Davis, CA 95616
R is a wonderful programming language for statistics and data management, used widely in industry, business, government, medicine and so on. And it's free, an open source product. The S language, of which R is essentially an open source version, won the ACM Software System Award in 1998.

Downloading R:

R is available for Linux, Windows and Mac systems.
You can download R from its home page.
For Ubuntu Linux or other Debian-related OSs, a more direct method is:
% sudo apt-get install r-base

Learning R:

There is a perception among some that R has a steep learning curve, but I disagree. True, R usage has its advanced aspects, but my recommendation is simply, just get started! Start simple, and then refine gradually.
I'll list a few tutorials below (not necessarily the best, just ones I know of). But first, I wish to make a very important point:
"When in doubt, try it out!" That's a slogan I invented to illustrate the point that R's interactive mode allows you to try your own little experiments, the best way to learn. Keep this in mind when you go through the tutorials listed below and in Google.
Here are some resources that I would recommend for learning R:

Advanced R:

R Programming Tools:

One of the most debated topics in R online discussions is that of programming tools for R, of which there are many.
  • I'm not a fan of integrated development environments, but if you like IDEs, there are a number of open source products available:
    • The most popular is undoubtedly RStudio, RStudio, introduced in 2011, and growing rapidly in functionality.
    • For fans of the Eclipse framework, StatET is available, and includes a debugging tool.
    • More established products include JGR, Rcmdr, RKWard.
    • There are a number of plugins for text editors such as Emacs (for which a debugger is available), Vim, gedit, and so on.
    • In the commercial realm, there is one from Revolution Analytics , which also includes a debugging tool.

People you can talk to:

  • There are various mailing lists (start with R-help) shown on the R home page.
  • There are R user groups in cities around the world. I'm active in the the San Francisco Bay Area group. We hold meetings once a month, with one or two speakers. Many attendees are new to R.
  • Another online place to ask questions is Stack Overflow.
©