Math 50, R Basics
Do not just read this document. Type each of the below commands in RStudio and get help from your R-group if needed.
4+3*2
c(1,12,123)
help(c)
myVector<-c(1,12,123)
myVector
-
Lets try to generate random numbers from uniform distribution and normal distributions. Try to google R uniform random number generation. In R studio help on “runif”
runif(n=5, min=10, max=20)
-
R uniform random number generation. In R studio help on “rnorm”
rnorm(n=5, mean = 11, sd = 7)
myData<-rnorm(n=100, mean = 11, sd = 7)
mean(myData)
var(myData)
sd(myData)
-
Tab Completion. Observe that you can get help about two different things: function and its arguments
-
type “var” then press tab
-
type “var(“ then press tab
-
Load data from a file or from a URL. Try those and observe erroneous loading in the first two read.table calls.
prop<-read.table("https://math.dartmouth.edu/~m50f17/propellant.csv")
prop
prop<-read.table("https://math.dartmouth.edu/~m50f17/propellant.csv", header=T)
prop
prop<-read.table("https://math.dartmouth.edu/~m50f17/propellant.csv", header=T, sep=”,”)
str(prop)
summary(prop)
fix(prop)
-
Lets try to calculate the mean of the second column of the table prop
prop$Age
prop[[2]]
mean(prop[[2]])
attach(prop)
Age
mean(Age)
-
Plotting Age vs Shear Strength
plot(prop)
plot(Age,ShearS)
plot(Age,ShearS, ylim=c(1600,2700))
propReverseOrder<-prop[2:1]
plot(propReverseOrder)
fitted<-lm(formula= ShearS ~ Age)
summary(fitted)
abline(fitted$coef, lwd=2, col=’blue’)
(Excercise try to use lm(formula= Age ~ ShearS) and see why it wont draw the line.
-
R Scripts. Save and Run following script
prop<-read.table("https://math.dartmouth.edu/~m50f17/propellant.csv", header=T, sep=",")
Age<-prop$Age
ShearS<-prop$ShearS
plot(Age,ShearS)
fitted<-lm(formula= ShearS ~ Age)
abline(fitted$coef, lwd=2, col=’blue’)
N<-length(Age)
yHat <- predict(fitted)
for (k in 1:N) lines(c(Age[k], Age[k]), c(ShearS[k], yHat[k]))