diff --git a/class-activity-2.Rmd b/class-activity-2.Rmd index e547dd9..3cbf5a4 100644 --- a/class-activity-2.Rmd +++ b/class-activity-2.Rmd @@ -1,7 +1,7 @@ --- -title: "intro to viz" -author: "Charles Lang" -date: "September 26, 2019" +title: "Class Activity 2" +author: "Ningyao Xu" +date: "September 28, 2019" output: html_document --- #Input @@ -17,7 +17,7 @@ D2 <- filter(D1, schoolyear == 20112012) ```{r} #Generate a histogramof the percentage of free/reduced lunch students (frl_percent) at each school -hist() +hist(D2$frl_percent) #Change the number of breaks to 100, do you get the same impression? @@ -32,7 +32,6 @@ hist(D2$frl_percent, breaks = 100, ylim = c(0,30)) hist(D2$frl_percent, breaks = c(0,10,20,80,100)) - ``` #Plots @@ -80,13 +79,24 @@ pairs(D5) #pmax sets a maximum value, pmin sets a minimum value #round rounds numbers to whole number values #sample draws a random samples from the groups vector according to a uniform distribution - +set.seed(123) +performance <- as.numeric(round(rnorm(100, 75, 15))) +Class <- c("sport","music","nature","literature") +Interest <- as.character(sample(Class, 100, replace = TRUE, prob = NULL)) +data1 <- as.data.frame(cbind(performance,Interest)) ``` 2. Using base R commands, draw a histogram of the scores. Change the breaks in your histogram until you think they best represent your data. ```{r} +#Generate a histogramof the scores +hist(performance) +min(performance) +max(performance) +#So the range of the performance is (40, 108). +#Then we Change the breaks so that they are 39-60(F), 60-70(D), 70-80(C),89-90(B),90-110(A). In this case, we can define their grade level directly based on the groups they are in. +hist(performance, breaks = c(39,60,70,80,90,110)) ``` @@ -95,6 +105,8 @@ pairs(D5) ```{r} #cut() divides the range of scores into intervals and codes the values in scores according to which interval they fall. We use a vector called `letters` as the labels, `letters` is a vector made up of the letters of the alphabet. +cut1 <- cut(performance,breaks = c(39,60,70,80,90,110),labels = letters[1:5]) +new_performance <- as.data.frame(cbind(performance,as.character(cut1))) ``` @@ -108,14 +120,20 @@ library(RColorBrewer) #Make RColorBrewer palette available to R and assign to your bins #Use named palette in histogram +library("ggplot2") +mypalette<-brewer.pal(5,"Greens") +ggplot(new_performance, aes(x=cut1))+ geom_histogram(stat="count",fill= mypalette,binwidth = 0.01,bins = 200) +scale_x_discrete(labels=c("F","D","C","B","A")) ``` +In this histogram, the greener the group is, the better performance students in that group have. + 5. Create a boxplot that visualizes the scores for each interest group and color each interest group a different color. ```{r} #Make a vector of the colors from RColorBrewer +boxplot(performance ~ data1$Interest,col=brewer.pal(4,"BrBG")) ``` @@ -123,13 +141,16 @@ library(RColorBrewer) 6. Now simulate a new variable that describes the number of logins that students made to the educational game. They should vary from 1-25. ```{r} - +set.seed(123) +(logins <- round(runif(100,min=1,max=25))) ``` 7. Plot the relationships between logins and scores. Give the plot a title and color the dots according to interest group. ```{r} +data1$logins <- logins +ggplot(data1, aes(logins, performance)) + geom_point(aes(colour = factor(Interest)))+scale_y_discrete(breaks = c(39,60,70,80,90,110),labels=c("F","D","C","B","A","")) ``` @@ -137,16 +158,39 @@ library(RColorBrewer) 8. R contains several inbuilt data sets, one of these in called AirPassengers. Plot a line graph of the the airline passengers over time using this data set. ```{r} - +plot(AirPassengers,xlab="Date", ylab = "Passenger numbers (1000's)",main="Air Passenger numbers from 1949 to 1961") ``` 9. Using another inbuilt data set, iris, plot the relationships between all of the variables in the data set. Which of these relationships is it appropraiet to run a correlation on? ```{r} - +my_cols <- c("#00AFBB", "#E7B800", "#FC4E07") +# Correlation panel +panel.cor <- function(x, y){ + usr <- par("usr"); on.exit(par(usr)) + par(usr = c(0, 1, 0, 1)) + r <- round(cor(x, y), digits=2) + txt <- paste0("R = ", r) + cex.cor <- 0.8/strwidth(txt) + text(0.5, 0.5, txt, cex = cex.cor * r) +} +# Customize upper panel +upper.panel<-function(x, y){ + points(x,y, pch = 19, cex =0.7, col = my_cols[iris$Species]) +} +# Create the plots +pairs(iris[,1:4], + lower.panel = panel.cor, + upper.panel = upper.panel) ``` +As we can see, there are three relationships that is appropraiet to run a correlation on, +1)The correlation coefficient between the length of sepal and length of petal is 0.87. +2)The correlation coefficient between the length of sepal and width of petal is 0.82. +3)The correlation coefficient between the length of petal and width of petal is 0.92. + + 10. Finally use the knitr function to generate an html document from your work. If you have time, try to change some of the output using different commands from the RMarkdown cheat sheet. 11. Commit, Push and Pull Request your work back to the main branch of the repository diff --git a/class-activity-2.html b/class-activity-2.html new file mode 100644 index 0000000..d368c42 --- /dev/null +++ b/class-activity-2.html @@ -0,0 +1,591 @@ + + + + + + + + + + + + + + + + +Class Activity 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + +

#Input

+
D1 <- read.csv("School_Demographics_and_Accountability_Snapshot_2006-2012.csv", header = TRUE, sep = ",")
+
+#Create a data frame only contains the years 2011-2012
+library(dplyr)
+
## 
+## Attaching package: 'dplyr'
+
## The following objects are masked from 'package:stats':
+## 
+##     filter, lag
+
## The following objects are masked from 'package:base':
+## 
+##     intersect, setdiff, setequal, union
+
D2 <- filter(D1, schoolyear == 20112012)
+

#Histograms

+
#Generate a histogramof the percentage of free/reduced lunch students (frl_percent) at each school
+
+hist(D2$frl_percent)
+

+
#Change the number of breaks to 100, do you get the same impression?
+
+hist(D2$frl_percent, breaks = 100)
+

+
#Cut the y-axis off at 30
+
+hist(D2$frl_percent, breaks = 100, ylim = c(0,30))
+

+
#Restore the y-axis and change the breaks so that they are 0-10, 10-20, 20-80, 80-100
+
+hist(D2$frl_percent, breaks = c(0,10,20,80,100))
+

+

#Plots

+
#Plot the number of English language learners (ell_num) by Computational Thinking Test scores (ctt_num) 
+
+plot(D2$ell_num, D2$ctt_num)
+

+
#Create two variables x & y
+x <- c(1,3,2,7,6,4,4)
+y <- c(2,4,2,3,2,4,3)
+
+#Create a table from x & y
+table1 <- table(x,y)
+
+#Display the table as a Barplot
+barplot(table1)
+

+
#Create a data frame of the average total enrollment for each year and plot the two against each other as a lines
+
+library(tidyr)
+
## 
+## Attaching package: 'tidyr'
+
## The following object is masked _by_ '.GlobalEnv':
+## 
+##     table1
+
D3 <- D1 %>% group_by(schoolyear) %>% summarise(mean_enrollment = mean(total_enrollment))
+
+plot(D3$schoolyear, D3$mean_enrollment, type = "l", lty = "dashed")
+

+
#Create a boxplot of total enrollment for three schools
+D4 <- filter(D1, DBN == "31R075"|DBN == "01M015"| DBN == "01M345")
+#The drop levels command will remove all the schools from the variable with not data  
+D4 <- droplevels(D4)
+boxplot(D4$total_enrollment ~ D4$DBN)
+

#Pairs

+
#Use matrix notation to select columns 5,6, 21, 22, 23, 24
+D5 <- D2[,c(5,6, 21:24)]
+#Draw a matrix of plots for every combination of variables
+pairs(D5)
+

# Exercise

+
    +
  1. Create a simulated data set containing 100 students, each with a score from 1-100 representing performance in an educational game. The scores should tend to cluster around 75. Also, each student should be given a classification that reflects one of four interest groups: sport, music, nature, literature.
  2. +
+
#rnorm(100, 75, 15) creates a random sample with a mean of 75 and standard deviation of 20
+#pmax sets a maximum value, pmin sets a minimum value
+#round rounds numbers to whole number values
+#sample draws a random samples from the groups vector according to a uniform distribution
+set.seed(123)
+performance <- as.numeric(round(rnorm(100, 75, 15)))
+Class <- c("sport","music","nature","literature")
+Interest <- as.character(sample(Class, 100, replace = TRUE, prob = NULL))
+data1 <- as.data.frame(cbind(performance,Interest))
+
    +
  1. Using base R commands, draw a histogram of the scores. Change the breaks in your histogram until you think they best represent your data.
  2. +
+
#Generate a histogramof the scores
+hist(performance)
+

+
min(performance)
+
## [1] 40
+
max(performance)
+
## [1] 108
+
#So the range of the performance is (40, 108).
+#Then we Change the breaks so that they are 39-60(F), 60-70(D), 70-80(C),89-90(B),90-110(A). In this case, we can define their grade level directly based on the groups they are in. 
+hist(performance, breaks = c(39,60,70,80,90,110))
+

+
    +
  1. Create a new variable that groups the scores according to the breaks in your histogram.
  2. +
+
#cut() divides the range of scores into intervals and codes the values in scores according to which interval they fall. We use a vector called `letters` as the labels, `letters` is a vector made up of the letters of the alphabet.
+cut1 <- cut(performance,breaks =  c(39,60,70,80,90,110),labels = letters[1:5])
+new_performance <- as.data.frame(cbind(performance,as.character(cut1)))
+
    +
  1. Now using the colorbrewer package (RColorBrewer; http://colorbrewer2.org/#type=sequential&scheme=BuGn&n=3) design a pallette and assign it to the groups in your data on the histogram.
  2. +
+
library(RColorBrewer)
+#Let's look at the available palettes in RColorBrewer
+
+#The top section of palettes are sequential, the middle section are qualitative, and the lower section are diverging.
+#Make RColorBrewer palette available to R and assign to your bins
+
+#Use named palette in histogram
+library("ggplot2")
+mypalette<-brewer.pal(5,"Greens")
+ggplot(new_performance, aes(x=cut1))+ geom_histogram(stat="count",fill= mypalette,binwidth = 0.01,bins = 200) +scale_x_discrete(labels=c("F","D","C","B","A"))
+
## Warning: Ignoring unknown parameters: binwidth, bins, pad
+

+

In this histogram, the greener the group is, the better performance students in that group have.

+
    +
  1. Create a boxplot that visualizes the scores for each interest group and color each interest group a different color.
  2. +
+
#Make a vector of the colors from RColorBrewer
+boxplot(performance ~ data1$Interest,col=brewer.pal(4,"BrBG"))
+

+
    +
  1. Now simulate a new variable that describes the number of logins that students made to the educational game. They should vary from 1-25.
  2. +
+
set.seed(123)
+(logins <- round(runif(100,min=1,max=25)))
+
##   [1]  8 20 11 22 24  2 14 22 14 12 24 12 17 15  3 23  7  2  9 24 22 18 16
+##  [24] 25 17 18 14 15  8  5 24 23 18 20  2 12 19  6  9  7  4 11 11 10  5  4
+##  [47]  7 12  7 22  2 12 20  4 14  6  4 19 22 10 17  3 10  8 21 12 20 20 20
+##  [70] 12 19 16 18  1 12  6 10 16  9  4  7 17 11 20  3 11 25 22 22  5  4 17
+##  [93]  9 17  9  6 20  3 12 13
+
    +
  1. Plot the relationships between logins and scores. Give the plot a title and color the dots according to interest group.
  2. +
+
data1$logins <- logins
+ggplot(data1, aes(logins, performance)) +  geom_point(aes(colour = factor(Interest)))+scale_y_discrete(breaks =  c(39,60,70,80,90,110),labels=c("F","D","C","B","A",""))
+

+
    +
  1. R contains several inbuilt data sets, one of these in called AirPassengers. Plot a line graph of the the airline passengers over time using this data set.
  2. +
+
plot(AirPassengers,xlab="Date", ylab = "Passenger numbers (1000's)",main="Air Passenger numbers from 1949 to 1961")
+

+
    +
  1. Using another inbuilt data set, iris, plot the relationships between all of the variables in the data set. Which of these relationships is it appropraiet to run a correlation on?
  2. +
+
my_cols <- c("#00AFBB", "#E7B800", "#FC4E07")
+# Correlation panel
+panel.cor <- function(x, y){
+    usr <- par("usr"); on.exit(par(usr))
+    par(usr = c(0, 1, 0, 1))
+    r <- round(cor(x, y), digits=2)
+    txt <- paste0("R = ", r)
+    cex.cor <- 0.8/strwidth(txt)
+    text(0.5, 0.5, txt, cex = cex.cor * r)
+}
+# Customize upper panel
+upper.panel<-function(x, y){
+  points(x,y, pch = 19, cex =0.7, col = my_cols[iris$Species])
+}
+# Create the plots
+pairs(iris[,1:4], 
+      lower.panel = panel.cor,
+      upper.panel = upper.panel)
+

+

As we can see, there are three relationships that is appropraiet to run a correlation on, 1)The correlation coefficient between the length of sepal and length of petal is 0.87. 2)The correlation coefficient between the length of sepal and width of petal is 0.82. 3)The correlation coefficient between the length of petal and width of petal is 0.92.

+
    +
  1. Finally use the knitr function to generate an html document from your work. If you have time, try to change some of the output using different commands from the RMarkdown cheat sheet.

  2. +
  3. Commit, Push and Pull Request your work back to the main branch of the repository

  4. +
+ + + + +
+ + + + + + + + + + + + + + + diff --git a/class-activity-2_NingyaoXu.Rproj b/class-activity-2_NingyaoXu.Rproj new file mode 100644 index 0000000..8e3c2eb --- /dev/null +++ b/class-activity-2_NingyaoXu.Rproj @@ -0,0 +1,13 @@ +Version: 1.0 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 2 +Encoding: UTF-8 + +RnwWeave: Sweave +LaTeX: pdfLaTeX