load the dataset called mtcars into your current workspace (it comes with R by default)
data("mtcars")
show the first few lines of mtcars data
head(mtcars)
view the mtcars data
View(mtcars)
show the documentation for the mtcars data
help(mtcars)
summarize the mtcars data
summary(mtcars)
access a single column of data, the mpg column
mtcars$mpg
access a single column of data, the wt column
mtcars$wt
perform a T-test comparing two variables
the tilde "~" means "explained by", so the following tests for an explanation of mpg by the car transmission type
t.test(mpg ~ am, data=mtcars)
assign the T-test result into a variable
tt = t.test(mpg ~ am, data=mtcars)
show the T-test on demand
tt
extract only the p-value
tt$p.value
extract only the confidence interval
tt$conf.int
perform a correlation test over two variables, mpg and wt
cor.test(mtcars$mpg, mtcars$wt)
assign the correlation test result into a variable
ct = cor.test(mtcars$mpg, mtcars$wt)
show the correlation test on demand
ct
extract only the p-value
ct$p.value
extract only the estimate
ct$estimate
extract only the confidence interval
ct$conf.int
create a linear model showing mpg explained by wt
fit = lm(mpg ~ wt, mtcars)
summarize the fit
summary(fit)
extract the matrix of coefficients
coef(summary(fit))
extract just the estimates of the matrix
co = coef(summary(fit))
get the first column
co[, 1]
get the fourth column
co[, 4]
use the predict function for our existing cars
predict(fit)
predict for a car at 4500 pounds
summarize the fit
summary(fit)
add together the intercept term (37.2851) and the weight coefficient
(-5.3445) times our new weight, which is 4.5 thousands of pounds
37.2851 + (-5.3445) * 4.5
use the built in predict function to get same answer as above
create a data frame containing the predictors we wish to use (4500 lbs)
newcar = data.frame(wt=4.5)
pass the predict function the new data frame
predict(fit, newcar)
plot out the linear model with a smoothing curve
plot12 <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + geom_smooth(method="lm") + ggtitle("Linear model of the relationship between a car weight and efficiency")
show plot
plot12
save the plot as a .png in your current working directory
ggsave(filename="cars.png", plot12)