So you have installed R!
One of the first
things you would like to do is getting help:
Given an R command or function x, entering ?x will bring up its help
file
> ?exp
The second command provides a list of help les in which the term
`exponential' can be found
in the concept or title.
> help.search("exponential")
R is case-sensitive, so foo, Foo and FOO are all considered different
names
> x = 3
> X
Error: object 'X' not found
> x
[1] 3
We can create matrices of values
> matrix(c(1, 2, 3, 4), nrow=2, ncol=2, byrow=TRUE)
> matrix(c(1, 2, 3, 4), nrow=2, ncol=2, byrow=FALSE)
Data frames are matrices, but they allow named columns and
non-numerical data
> s <- data.frame(FirstVar=c(1:10), SecondVar='A')
> dim(s)
Pressing the arrow keys cycles through previous commands
A better way is to write your code as an R script. To do so, select
`File/New script'. R scripts can then
be saved and re-used when necessary. A saved script can be run with `File/Source
R code'.
Alternatively, you can highlight any part of previously written code
and run it by pressing `Ctrl' +`R'
Consider the 'trees' data set, that provides measurements of the girth,
height and
volume of timber in 31 felled black cherry trees.
> trees
R can provide very quick summary information
> summary(trees)
> names(trees)
> sd(trees)
> boxplot(trees)
> pairs(trees)
> hist(trees$Height)
> plot(trees$Height, trees$Volume)
> for (i in 1:3) { plot(density(trees[,i]), xlab="Value",
main=names(trees)[i]) }
Individual variables can be directly named if we 'attach' the data
frame to the current workspace
> attach(trees)
> Girth
The <tab> key completes a name (to the best it can!), much like
linux/Unix systems files
Can we model Volume from the Girth and Height?
> plot(Girth,Volume)
> abline( lm(Volume ~ Girth) )
We can make more complicated (though still linear) models
> model2 <- lm(log(Volume) ~ Girth + I(Girth^2))
We can get (or set) the names of an object
> names(model2)
and its attributes
>attributes(model2)
>model2$fitted.values
or display the internal structure of an object
> str(trees)
> str(model)
though in general summary will be enough
>summary(model2)
Let's do some iteration and conditioning
>for (i in 1:10) if ((g<-rnorm(1))>0.25) { cat(paste(i,
round(g,4),"\n")) } else { cat("no!\n") }
and some function definition
>drawCards = function (number)
{
faceValues = c(1:10, "Jack", "Queen", "King")
suits = c("Hearts", "Diamonds", "Spades", "Clubs")
f = sample(faceValues, number, replace=TRUE)
s = sample(suits, number, replace=TRUE)
paste(f, "of", s)
}
> drawCards(5)
Note that the function returns as value the result of its last
evaluation