Statistics for Laboratory Scientists ( 140.615 )

R as a calculator

The below is based in part on a script from John Fox.

Basic arithmetic

2+3
## [1] 5
2-3
## [1] -1
2*3
## [1] 6
2/3
## [1] 0.6666667
2^3
## [1] 8

Precedence of operators

4^2-3*2
## [1] 10
(4^2)-(3*2) # better: use parentheses to group and clarify
## [1] 10
4^(2-3)*2
## [1] 0.5
1-6+4
## [1] -1
2^-3
## [1] 0.125
2^(-3)
## [1] 0.125
-2--3
## [1] 1
(-2)-(-3)
## [1] 1

Functions, obtaining help

log(100)
## [1] 4.60517
?log
help(log)
log(100,base=10)
## [1] 2
log(100,b=10)
## [1] 2
log(100,10)
## [1] 2
log10(100)
## [1] 2
help.search("log")
??log

Vectorized arithmetic

c(1,2,3,4) 
## [1] 1 2 3 4
1:4   
## [1] 1 2 3 4
4:1
## [1] 4 3 2 1
-1:2 # note the precedence
## [1] -1  0  1  2
(-1):2
## [1] -1  0  1  2
seq(1,4)
## [1] 1 2 3 4
seq(2,8,by=2)
## [1] 2 4 6 8
seq(0,1,by=0.1)
##  [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
seq(0,1,length=11)
##  [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
c(1,2,3,4)/2    
## [1] 0.5 1.0 1.5 2.0
c(1,2,3,4)/c(4,3,2,1)
## [1] 0.2500000 0.6666667 1.5000000 4.0000000
log10(c(0.1,1,10,100))
## [1] -1  0  1  2
log2(c(1,2,4,8,16,32))
## [1] 0 1 2 3 4 5

Basic summaries.

x <- c(1,3.5,-28.4,10)
x
## [1]   1.0   3.5 -28.4  10.0
sum(x)
## [1] -13.9
prod(x)
## [1] -994
mean(x)
## [1] -3.475

Missing data points.

x <- c(1,5,10,NA,15)
x
## [1]  1  5 10 NA 15
sum(x)
## [1] NA
sum(x,na.rm=TRUE)
## [1] 31
prod(x,na.rm=TRUE)
## [1] 750
mean(x,na.rm=TRUE)
## [1] 7.75

More on creating simple vectors

rep(2,10)
##  [1] 2 2 2 2 2 2 2 2 2 2
rep(1:3,4)
##  [1] 1 2 3 1 2 3 1 2 3 1 2 3
rep(1:3,c(4,4,4))
##  [1] 1 1 1 1 2 2 2 2 3 3 3 3
rep(1:3,rep(4,3))
##  [1] 1 1 1 1 2 2 2 2 3 3 3 3
rep(1:3,each=4)
##  [1] 1 1 1 1 2 2 2 2 3 3 3 3
rep(c(1,2,3),c(2,4,5))
##  [1] 1 1 2 2 2 2 3 3 3 3 3

Numeric, character, logic.

c(1,3.5,-28.4,10)
## [1]   1.0   3.5 -28.4  10.0
c("cat","dog","mouse","monkey")
## [1] "cat"    "dog"    "mouse"  "monkey"
c(TRUE,TRUE,TRUE,FALSE,FALSE)
## [1]  TRUE  TRUE  TRUE FALSE FALSE