| Read each question carefully and address each element. Do not output contents of vectors or data frames unless requested. |
| ##### Section 1: (8 points) This problem deals with vector manipulations. |
| (1)(a) Create a vector that contains the following, in this order, and output the final, resulting vector. Do not round any values, unless requested. * A sequence of integers from 0 to 4, inclusive. * The number 13 * Three repetitions of the vector c(2, -5.1, -23). * The arithmetic sum of 7/42, 3 and 35/42 |
r result <- c(seq(0,4,1), 13, rep(c(2,-5.1,-23),3), ((7/42) + 3 + (35/42))) print(result) |
## [1] 0.0 1.0 2.0 3.0 4.0 13.0 2.0 -5.1 -23.0 2.0 -5.1 -23.0 ## [13] 2.0 -5.1 -23.0 4.0 |
| (1)(b) Sort the vector created in (1)(a) in ascending order. Output this result. Determine the length of the resulting vector and assign to “L”. Output L. Generate a descending sequence starting with L and ending with 1. Add this descending sequence arithmetically the sorted vector. This is vector addition, not vector combination. Output the contents. Do not round any values. |
r f=sort(result,decreasing=FALSE) print(f) |
## [1] -23.0 -23.0 -23.0 -5.1 -5.1 -5.1 0.0 1.0 2.0 2.0 2.0 2.0 ## [13] 3.0 4.0 4.0 13.0 |
r L=length(f) print(L) |
## [1] 16 |
r g=seq(from=L,to=1,by=-1) print(g) |
## [1] 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 |
r h=f+g print(h) |
## [1] -7.0 -8.0 -9.0 7.9 6.9 5.9 10.0 10.0 10.0 9.0 8.0 7.0 7.0 7.0 6.0 ## [16] 14.0 |
| (1)(c) Extract the first and last elements of the vector you have created in (1)(b) to form another vector of the extracted elements. Form a third vector from the elements not extracted. Output these vectors. |
r extracted=h[c(1,16)] print(extracted) |
## [1] -7 14 |
r remaining=h[seq(2,15)] print(remaining) |
## [1] -8.0 -9.0 7.9 6.9 5.9 10.0 10.0 10.0 9.0 8.0 7.0 7.0 7.0 6.0 |
| (1)(d) Use the vectors from (c) to reconstruct the vector in (b). Output this vector. Sum the elements and round to two decimal places. |
r cccombo <- c(extracted,remaining) print (cccombo) |
## [1] -7.0 14.0 -8.0 -9.0 7.9 6.9 5.9 10.0 10.0 10.0 9.0 8.0 7.0 7.0 7.0 ## [16] 6.0 |
r signif(sum(cccombo), digits=4) |
## [1] 84.7 |
(2)(a) Create a user-defined function - via function() - that implements the trigonometric function above, accepts numeric values, “x,” calculates and returns values “y.”
trig <- function(x)
y <- sin(x/2) + cos(x/2)
(2)(b) Create a vector, x, of 4001 equally-spaced values from -2 to 2, inclusive. Compute values for y using the vector x and your function from (2)(a). Do not output x or y. Find the value in the vector x that corresponds to the maximum value in the vector y. Restrict attention to only the values of x and y you have computed; i.e. do not interpolate. Round to 3 decimal places and output both the maximum y and corresponding x value.
Finding the two desired values can be accomplished in as few as two lines of code. Do not use packages or programs you may find on the internet or elsewhere. Do not output the other elements of the vectors x and y. Relevant coding methods are given in the Quick Start Guide for R.
x <- seq(-2,2,length=4001)
y <- trig(x)
xmax <- round(x[which.max(y)], 3)
ymax <- round(max(y), 3)
print(xmax)
## [1] 1.571
print(ymax)
## [1] 1.414
(2)(c) Plot y versus x in color, with x on the horizontal axis. Show the location of the maximum value of y determined in 2(b). Show the values of x and y corresponding to the maximum value of y in the display. Add a title and other features such as text annotations. Text annotations may be added via text() for base R plots and geom_text() or geom_label() for ggplots.
plot(x,y, type = "l",col = "red", main = "sin(x/2) + cos(x/2)")
points(x = xmax, y = ymax, col = "blue", pch = 19)
text(1.5,1.3, "(1.571, 1.414)")
y1 <- cos(x/2) * sin(x/2)
y2 <- -(x/2)^3
intersect(y1,y2)
## [1] 0
plot(x, y1, type = "b", pch = 19, cex = 0.4, col="blue",
xlab = "x", ylab = "y", main = "plot intersection")
lines(x, y2, lty = 2, lwd = 2)
legend("bottom", inset = 0.03, legend=c("cos(x/2) * sin(x/2)","- (x/2) ^ 3"),
col=c("blue","black"),lty=1:2, cex=0.7)
points(0,0)
text(-.1,.1, '(0, 0)', pos = 3)
(4)(a) Use data(trees) to load the dataset. Check and output the structure with str(). Use apply() to return the median values for the three variables. Output these values. Using R and logicals, output the row number and the three measurements - Girth, Height and Volume - of any trees with Girth equal to median Girth. It is possible to accomplish this last request with one line of code.
data(trees)
str(trees)
## 'data.frame': 31 obs. of 3 variables:
## $ Girth : num 8.3 8.6 8.8 10.5 10.7 10.8 11 11 11.1 11.2 ...
## $ Height: num 70 65 63 72 81 83 66 75 80 75 ...
## $ Volume: num 10.3 10.3 10.2 16.4 18.8 19.7 15.6 18.2 22.6 19.9 ...
apply(trees, 2, median)
## Girth Height Volume
## 12.9 76.0 24.2
print(trees[which(trees$Girth == median(trees$Girth)),])
## Girth Height Volume
## 16 12.9 74 22.2
## 17 12.9 85 33.8
(4)(b) Girth is defined as the diameter of a tree taken at 4 feet 6 inches from the ground. Convert each diameter to a radius, r. Calculate the cross-sectional area of each tree using pi times the squared radius. Present a stem-and-leaf plot of the radii, and a histogram of the radii in color. Plot Area (y-axis) versus Radius (x-axis) in color showing the individual data points. Label appropriately.
r <- trees$Girth/2
Area <- pi*r^2
stem(r)
##
## The decimal point is at the |
##
## 4 | 234
## 5 | 34455667779
## 6 | 055799
## 7 | 013
## 8 | 0278
## 9 | 000
## 10 | 3
hist(r, col = c("orange","blue","green","purple","red","black","pink"), main = "Tree area as a function of radius")
plot(r,Area,col="blue",main="Tree areas vs the Radius",xlab="Tree Radius",ylab="Area of Tree")
(4)(c) Present a horizontal, notched, colored boxplot of the areas calculated in (b). Title and label the axis.
boxplot(Area, notch = TRUE, col = "green", main = "Cross-sectional area boxplot",
xlab = expression(paste("Cross-sectional area (in"^"2",")")), horizontal = TRUE)
(4)(d) Demonstrate that the outlier revealed in the boxplot of Volume is not an extreme outlier. It is possible to do this with one line of code using boxplot.stats() or ‘manual’ calculation and logicals. Identify the tree with the largest area and output on one line its row number and three measurements.
boxplot.stats(Area, coef = 3)$out #there are no extreme outliers
## numeric(0)
witharea <- cbind(trees, Area)
print(witharea[which(witharea$Area == max(witharea$Area)),])
## Girth Height Volume Area
## 31 20.6 87 77 333.2916
5(a) Use set.seed(124) and rexp() with n = 100, rate = 5.5 to generate a random sample designated as y. Generate a second random sample designated as x with set.seed(127) and rnorm() using n = 100, mean = 0 and sd = 0.15.
Generate a new object using cbind(x, y). Do not output this object; instead, assign it to a new name. Pass this object to apply() and compute the inter-quartile range (IQR) for each column: x and y. Use the function IQR() for this purpose. Round the results to four decimal places and present (this exercise shows the similarity of the IQR values.).
For information about rexp(), use help(rexp) or ?rexp(). Do not output x or y.
set.seed(124)
y <- rexp(100,5.5)
set.seed(127)
x <- rnorm(100,0,.15)
combined <- cbind(x, y)
round(apply(combined,2,IQR),4)
## x y
## 0.2041 0.2164
(5)(b) This item will illustrate the difference between a right-skewed distribution and a symmetric one. For base R plots, use par(mfrow = c(2, 2)) to generate a display with four diagrams; grid.arrange() for ggplots. On the first row, for the normal results, present a histogram and a horizontal boxplot for x in color. For the exponential results, present a histogram and a horizontal boxplot for y in color.
par(mfrow = c(2,2))
hist(x, col= "red")
boxplot(x, col = "green", main = "Boxplot of X", xlab = "x", horizontal = TRUE)
hist(y, col = "blue")
boxplot(y, col = "orange", main = "Boxplot of y", xlab = "y", horizontal = TRUE)
(5)(c) QQ plots are useful for detecting the presence of heavy-tailed distributions. Present side-by-side QQ plots, one for each sample, using qqnorm() and qqline(). Add color and titles. In base R plots, “cex” can be used to control the size of the plotted data points and text. Lastly, determine if there are any extreme outliers in either sample.Remember extreme outliers are based on 3.0IQR in the box plot. R uses a default value of 1.5IQR to define outliers (not extreme) in both boxplot and boxplot stats.
par(mfrow = c(1,2))
qqnorm(x, main = "QQ plot for X", col = "blue")
qqline(x)
legend("topleft", inset = 0.03, legend=c("data","qq line"),col=c("blue","black"),
lty= c(NA,1), pch=c(21), cex=0.75)
qqnorm(y, main = "QQ plot for Y", col = "red")
qqline(y)
legend("topleft", inset = 0.03, legend=c("data","qq line"),col=c("red","blue"),
lty= c(NA,1), pch=c(21), cex=0.75)
boxplot.stats(x, coef = 3)$out #Ran for x, no extreme outliers
## numeric(0)
boxplot.stats(y, coef = 3)$out #Ran for y, extreme outlier is 1.448679
## [1] 1.448679