College.csv. It contains a number of variables for 777 different universities and colleges in the US. Obs: For this question, i did not use the csv file, the file was not found when i called it after loaded College dataset, so i had to skip some questions.
a) Use the read.csv() function to read the data into R. Call the loaded data college. Make sure that you have the directory set to the correct location for the data.
library(ISLR)
data(College)
college <- College
attach(college)
c) Now, you should see that the first data column is Private. Note that another column labeled row.names now appears before the Private column. However, this is not a data column but rather the name that R is giving to each row.
I. Use the summary() function to produce a numerical summary of the variables in the data set.
summary(college)
## Private Apps Accept Enroll Top10perc
## No :212 Min. : 81 Min. : 72 Min. : 35 Min. : 1.00
## Yes:565 1st Qu.: 776 1st Qu.: 604 1st Qu.: 242 1st Qu.:15.00
## Median : 1558 Median : 1110 Median : 434 Median :23.00
## Mean : 3002 Mean : 2019 Mean : 780 Mean :27.56
## 3rd Qu.: 3624 3rd Qu.: 2424 3rd Qu.: 902 3rd Qu.:35.00
## Max. :48094 Max. :26330 Max. :6392 Max. :96.00
## Top25perc F.Undergrad P.Undergrad Outstate
## Min. : 9.0 Min. : 139 Min. : 1.0 Min. : 2340
## 1st Qu.: 41.0 1st Qu.: 992 1st Qu.: 95.0 1st Qu.: 7320
## Median : 54.0 Median : 1707 Median : 353.0 Median : 9990
## Mean : 55.8 Mean : 3700 Mean : 855.3 Mean :10441
## 3rd Qu.: 69.0 3rd Qu.: 4005 3rd Qu.: 967.0 3rd Qu.:12925
## Max. :100.0 Max. :31643 Max. :21836.0 Max. :21700
## Room.Board Books Personal PhD
## Min. :1780 Min. : 96.0 Min. : 250 Min. : 8.00
## 1st Qu.:3597 1st Qu.: 470.0 1st Qu.: 850 1st Qu.: 62.00
## Median :4200 Median : 500.0 Median :1200 Median : 75.00
## Mean :4358 Mean : 549.4 Mean :1341 Mean : 72.66
## 3rd Qu.:5050 3rd Qu.: 600.0 3rd Qu.:1700 3rd Qu.: 85.00
## Max. :8124 Max. :2340.0 Max. :6800 Max. :103.00
## Terminal S.F.Ratio perc.alumni Expend
## Min. : 24.0 Min. : 2.50 Min. : 0.00 Min. : 3186
## 1st Qu.: 71.0 1st Qu.:11.50 1st Qu.:13.00 1st Qu.: 6751
## Median : 82.0 Median :13.60 Median :21.00 Median : 8377
## Mean : 79.7 Mean :14.09 Mean :22.74 Mean : 9660
## 3rd Qu.: 92.0 3rd Qu.:16.50 3rd Qu.:31.00 3rd Qu.:10830
## Max. :100.0 Max. :39.80 Max. :64.00 Max. :56233
## Grad.Rate
## Min. : 10.00
## 1st Qu.: 53.00
## Median : 65.00
## Mean : 65.46
## 3rd Qu.: 78.00
## Max. :118.00
pairs() function to produce a scatterplot matrix of the first ten columns or variables of the data. Recall that you can reference the first ten columns of a matrix A using A[, 1:10].pairs(college[, 1:10])
plot() function to produce side-by-side boxplots of Outstate versus Private.plot(Private, Outstate, varwidth=T, col="red",
xlab="Private College", ylab="Out-of-State Tuition in USD",
main="Distribution Along the Colleges")
Elite, by binning the Top10perc variable. We are going to divide universities into two groups based on whether or not the proportion of students coming from the top 10% of their high school classes exceeds 50%.Elite=rep("No", nrow(college))
Elite[college$Top10perc>50]="Yes"
Elite=as.factor(Elite)
college=data.frame(college, Elite)
Use the summary() function to see how many elite universities there are. Now use the plot() function to produce side-by-side boxplots of Outstate versus Elite.
summary(Elite)
## No Yes
## 699 78
plot(Elite, Outstate, varwidth=T, col="red",
xlab="Elite College", ylab="Out-of-State Tuition in USD",
main="Distribution Along the Elite Colleges")
V. Use the hist() function to produce some histograms with differing numbers of bins for a few of the quantitative variables. You may find the command par(mfrow=c(2,2)) useful: it will divide the print window into four regions so that four plots can be made simultaneously. Modifying the arguments to this function will divide the screen in other ways.
par(mfrow=c(2,2))
hist(Top10perc, breaks=10, col="red", main="Percentage of The Top10 H.S. Students")
hist(Apps, breaks=10, col="orange", main="Number of New Applications Received")
hist(Personal, breaks=10, col="green", main="Estimated Personal Spending")
hist(PhD, breaks=10, col="blue", main="Percentage of Faculty with Ph.D.'s")
summary(PhD)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 8.00 62.00 75.00 72.66 85.00 103.00
It is strange that there is a college with more than 100% of percentage, checking the college or colleges.
row.names(college[PhD>100, ])
## [1] "Texas A&M University at Galveston"
Also there’s an isolated university who receive a very larger number of applications than others, approximately 50 thousands.
summary(Apps)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 81 776 1558 3002 3624 48090
row.names(college[Apps>25000, ])
## [1] "Rutgers at New Brunswick"
Detaching the College data set.
detach(college)
Auto data set studied in the lab. Make sure that the missing values have been removed from the data.The function NA.omit removes all incomplete cases.
data(Auto)
auto <- na.omit(Auto)
attach(auto)
a) Which of the predictors are quantitative, and which are qualitative?
lapply(auto, class)
## $mpg
## [1] "numeric"
##
## $cylinders
## [1] "numeric"
##
## $displacement
## [1] "numeric"
##
## $horsepower
## [1] "numeric"
##
## $weight
## [1] "numeric"
##
## $acceleration
## [1] "numeric"
##
## $year
## [1] "numeric"
##
## $origin
## [1] "numeric"
##
## $name
## [1] "factor"
The column name is the only not numeric, therefore it is a qualitative. Also reading the data set information ?Auto, it is seen that the origin column is qualitative, factors described as numbers. The other columns are all quantitatives.
origin <- as.factor(origin)
b) What is the range of each quantitative predictor? You can answer this range() function.
# columns qualitative
cols.qlt = names(auto) %in% c("name", "origin")
# apply range in all columns except the qualitative
lapply(auto[, !cols.qlt], range)
## $mpg
## [1] 9.0 46.6
##
## $cylinders
## [1] 3 8
##
## $displacement
## [1] 68 455
##
## $horsepower
## [1] 46 230
##
## $weight
## [1] 1613 5140
##
## $acceleration
## [1] 8.0 24.8
##
## $year
## [1] 70 82
c) What is the mean and standard deviation of each quantitative predictor?
lapply(auto[, !cols.qlt], function(x){ c('mean'=mean(x), 'sd'=sd(x))})
## $mpg
## mean sd
## 23.445918 7.805007
##
## $cylinders
## mean sd
## 5.471939 1.705783
##
## $displacement
## mean sd
## 194.412 104.644
##
## $horsepower
## mean sd
## 104.46939 38.49116
##
## $weight
## mean sd
## 2977.5842 849.4026
##
## $acceleration
## mean sd
## 15.541327 2.758864
##
## $year
## mean sd
## 75.979592 3.683737
d) Now remove the 10th through 85th observations. What is the range, mean, and standard deviation of each predictor in the subset of the data that remains?
lapply(auto[-(10:85), !cols.qlt], function(x){ c('mean'=mean(x), 'sd'=sd(x))})
## $mpg
## mean sd
## 24.404430 7.867283
##
## $cylinders
## mean sd
## 5.373418 1.654179
##
## $displacement
## mean sd
## 187.24051 99.67837
##
## $horsepower
## mean sd
## 100.72152 35.70885
##
## $weight
## mean sd
## 2935.9715 811.3002
##
## $acceleration
## mean sd
## 15.726899 2.693721
##
## $year
## mean sd
## 77.145570 3.106217
e) Using the full data set, investigate the predictors graphically, using scatterplots or other tools of your choice. Create some plots highlighting the relationships among the predictors. Comment on your findings.
pairs(auto[, !cols.qlt])
Perceiving the graph, it is noticed many tends, some instances are mpg x cylinders, horsepower x weight, mpg x weight and displacement x acceleration. Visualize it closer.
par(mfrow=c(2,2))
plot(displacement, acceleration)
plot(weight, horsepower)
plot(cylinders, mpg)
plot(weight, mpg)
There is a linear tendency in all four graphs: mpg tends to decrease as cylinders or weight increases, whereas horsepower increases as weight increases, and acceleration and displacement have a negative correlation.
f) Suppose that we wish to predict gas mileage (mpg) on the basis of the other variables. Do your plots suggest that any of the other variables might be useful in predicting mpg? Justify your answer.
others.variables = !(names(auto) %in% "mpg" | cols.qlt)
par(mfrow=c(3,2))
for(i in names(auto[, others.variables])){
plot(mpg, get(i), ylab=i)
}
How seen in the graphs, all other variables seems to have some correlation with mpg in distinct levels.
Boston housing data set.a) To begin, load in the Boston data set. The Boston data set is part of the MASS library in R.
library(MASS)
Now the data set is contained in the object Boston.
Boston
Read about the data set:
?Boston
How many rows are in this data set? How many columns? What do the rows and columns represent?
The command dim computes the rows and columns of the dataset.
dim(Boston)
## [1] 506 14
The rows represent observations of the U.S. Census Tracts in the Boston Area. The columns presents the measures of the Census Variables.
b) Make some pairwise scatterplot of the predictors (columns) in this data set. Describe your findings.
attach(Boston)
pairs(Boston)
An interesting finding is that high level of rad - index of accessibility to radial highways contain the highest level of cri - per capita crime rate by town.
Seemingly, medv has an inversely proportion to lstat - lower status of the population,nox - nitrogen oxides concentration and indus - proportion of non-retail business acres per town, and a direct proportion to rm - average number of rooms per dwelling.
c) Are any of the predictors associated with per capita crime rate? If so, explain the relationship.
Indexes of correlations between crime rates and other variables. Printing them in order of absolutes values.
Boston.corr = cor(Boston)
Boston.corr.crim = Boston.corr[-1,1]
print(
Boston.corr.crim[order(abs(Boston.corr.crim), decreasing = T)]
)
## rad tax lstat nox indus medv
## 0.62550515 0.58276431 0.45562148 0.42097171 0.40658341 -0.38830461
## black dis age ptratio rm zn
## -0.38506394 -0.37967009 0.35273425 0.28994558 -0.21924670 -0.20046922
## chas
## -0.05589158
The four greatest correlation values have a positive relationship, plotting them:
par(mfrow=c(2,2))
# get the four most correlated variables
aux = names(Boston.corr.crim[order(abs(Boston.corr.crim), decreasing = T)][1:4])
for(i in aux){
plot(get(i), crim, xlab=i)
}
d) Do any of the suburbs of Boston appear to have particularly high crime rates? Tax rates? Pupil-teacher ratios? Comment on the range of each predictor.
Crime Rates
summary(crim)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.00632 0.08204 0.25650 3.61400 3.67700 88.98000
Yes, the maximum value is much higher than the 3th quartile. Counting crime rates abouve 30.
length(crim[crim>30])
## [1] 8
Tax Rates
hist(tax)
There are particulary suburbs in a higher level, counting values above 500.
length(tax[tax>500])
## [1] 137
Pupil-Teacher Ratio
hist(ptratio)
It seems a bit equilibrate between values of [14, 22], specially [20,21]. Counting values bellow 14 - the smallest ratios.
length(ptratio[ptratio<14])
## [1] 16
e) How many of the suburbs in this data set bound the Charles river?
table(chas)
## chas
## 0 1
## 471 35
The value 1 says that the suburb bounds the Charles Rivers, there are 35 suburbs that bound river.
f) What is the median pupil-teacher ration among the towns in this data set?
median(ptratio)
## [1] 19.05
g) Which suburb of Boston has lowest median value of owner-occupied homes? What are the values of the other predictors for that suburb, and how do those values compare to the overall ranges for those predictors? Comment on your findings.
The suburbs of which are lower than median:
subs.lw = which(medv<median(medv))
print(subs.lw)
## [1] 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 26 27
## [18] 28 29 30 31 32 33 34 35 36 37 38 46 47 48 49 50 51
## [35] 52 55 60 61 62 67 69 70 77 78 80 95 103 104 105 106 107
## [52] 108 109 110 113 114 115 116 118 119 120 122 123 124 125 127 128 129
## [69] 130 131 132 134 135 136 137 138 139 140 141 142 143 144 145 146 147
## [86] 148 149 150 152 153 154 155 156 157 171 172 210 212 242 245 246 248
## [103] 256 270 271 287 298 310 311 313 316 317 318 320 323 324 329 331 332
## [120] 333 335 336 337 338 339 340 341 343 346 347 353 355 356 357 362 363
## [137] 364 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
## [154] 390 391 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
## [171] 409 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
## [188] 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
## [205] 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
## [222] 461 462 463 464 466 467 468 469 470 471 472 475 476 477 478 479 485
## [239] 487 488 489 490 491 492 493 497 498 500 501 503 506
Compare with the rest of the other predictors.
Boston.corr.subs.lw = cor(Boston[subs.lw, ])
corr.compare = data.frame('lower'=Boston.corr.subs.lw[, "medv"], 'all'=Boston.corr[, "medv"])
corr.compare$diff = corr.compare$lower - corr.compare$all
Check how much vary the differences.
hist(corr.compare$diff, xlab="Correlation Differences")
Now, in absolute values.
hist(abs(corr.compare$diff), xlab="Correlation Differences")
The main correlation diffences were at the variables:
main.diffs = head(corr.compare[order(abs(corr.compare$diff), decreasing = T), ], 5)
print(main.diffs)
## lower all diff
## rm 0.1493689 0.6953599 -0.5459910
## ptratio -0.1971183 -0.5077867 0.3106684
## dis 0.4815516 0.2499287 0.2316229
## crim -0.5857651 -0.3883046 -0.1974605
## rad -0.5380354 -0.3816262 -0.1564092
print(rownames(main.diffs))
## [1] "rm" "ptratio" "dis" "crim" "rad"
The abrupt difference by far was rm - average number of rooms per dwelling, so the number of rooms has much less influence in the cheapest houses than the more expensive ones, this phenomenon also seem happening in ptratio. The dis increased compared to all suburbs correlation, it seems that further from employment centres is better for cheaper house prices.
h) In this data set, how many of the suburbs average more than seven rooms per dwelling? More than eight rooms per dwelling? Comment on the suburbs that average more than eight rooms per dwelling.
hist(rm, main="Distribution of Rooms by Dwelling", xlab="Rooms")
More than 7 rooms per dwelling
length(rm[rm>7])
## [1] 64
More than 8 rooms per dwelling
length(rm[rm>8])
## [1] 13
Let’s see the prices of these houses compared over all others suburb houses.
frm =as.factor(as.character(lapply(rm, function(x) ifelse(x>8, "]8, +Inf[", ifelse(x>7,"]7,8]","[0,7]")))))
plot(frm, medv, varwidth=T, xlab="Number of Rooms",
ylab="Median Values by $1000s",
title="Median Value of Owner-Occupied Homes")
The graph shows that houses of more than 8 rooms tend to be much more expensive, but not always, and even an outlier exists of very lower price than houses with less rooms, as seen below.
Boston[rm>8 & medv<30, ]
## crim zn indus chas nox rm age dis rad tax ptratio black
## 365 3.47428 0 18.1 1 0.718 8.78 82.9 1.9047 24 666 20.2 354.55
## lstat medv
## 365 5.29 21.9