Jake Feldman
We will work with a built in data frame called chickweights
Create a boxplot for the weights of the chicks by feed
Create a plot that shows how many chickens received each type of feed.
head(chickwts)
weight feed
1 179 horsebean
2 160 horsebean
3 136 horsebean
4 227 horsebean
5 217 horsebean
6 168 horsebean
str(chickwts)
'data.frame': 71 obs. of 2 variables:
$ weight: num 179 160 136 227 217 168 108 124 143 140 ...
$ feed : Factor w/ 6 levels "casein","horsebean",..: 2 2 2 2 2 2 2 2 2 2 ...
ggplot(chickwts, aes(feed, weight)) + geom_boxplot()
ggplot(chickwts, aes(feed)) + geom_bar() +
labs(title= "Number of Chicks Receiving Each Feed")
Plotting two data frames on one graph
#First lets create a data frame that has the info sorted by the number of cylinders
mtcars_sorted_bycyl = mtcars[order(mtcars$cyl),]
mtcars_4cyl=mtcars_sorted_bycyl[1:11,]
mtcars_6cyl=mtcars_sorted_bycyl[12:18,]
#This is how we can plot things from teo different data frames
plot = ggplot() + geom_point(data = mtcars_4cyl, aes(hp, mpg ,color = "4 cylinder")) +
geom_point(data = mtcars_6cyl, aes(hp, mpg, color = "6 cylinder")) +
scale_colour_manual(values = c("4 cylinder"="blue", "6 cylinder"="red"))
plot
-We will be using an R package called sqldf to issue our SQL queries
-We will use SQL to filter/sort/group rows of a data frame(s).
-We will keep adding on tools that we can use within SQL queries
-The syntax here is the exact same as if you were working with a MySQL database
head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
-I like to put SQL syntax in all caps for readability
-Query must be a string (so put it in double quotes)
-You must be querying from a data frame
-Package sqldf does not like periods in column names
-SQL queries using sqldf return data frames
-SELECT column_names FROM df_name
-We can do a lot with just the basic select statement
#Select all rows but specific columns
df = sqldf("SELECT mpg, cyl FROM mtcars")
Loading required package: tcltk
head(df)
mpg cyl
1 21.0 6
2 21.0 6
3 22.8 4
4 21.4 6
5 18.7 8
6 18.1 6
#Select all the columns + rows from mtcars
df = sqldf("SELECT * FROM mtcars")
head(df)
mpg cyl disp hp drat wt qsec vs am gear carb
1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
-Sometimes it is useful to rename or alias columns. We can do this with the AS command.
More readable
Make names easier to type
#vs was ambiguous so here I gave it a more appropriate name
df = sqldf("SELECT mpg, cyl, vs AS Engine FROM mtcars")
head(df)
mpg cyl Engine
1 21.0 6 0
2 21.0 6 0
3 22.8 4 1
4 21.4 6 1
5 18.7 8 0
6 18.1 6 1
#Need to use single quotes when using alias that is more than one word
df = sqldf("SELECT mpg, cyl, vs AS 'Engine Type' FROM mtcars")
head(df)
mpg cyl Engine Type
1 21.0 6 0
2 21.0 6 0
3 22.8 4 1
4 21.4 6 1
5 18.7 8 0
6 18.1 6 1
#We can create new column that are functions of other columns
#using the SELECT statement
df = sqldf("SELECT mpg, cyl, (mpg/cyl) AS 'mpg per cyl' FROM mtcars")
head(df)
mpg cyl mpg per cyl
1 21.0 6 3.500000
2 21.0 6 3.500000
3 22.8 4 5.700000
4 21.4 6 3.566667
5 18.7 8 2.337500
6 18.1 6 3.016667
#Selecting only distinct rows. Can use this to clean the data or
#just look at unique rows
df = sqldf("SELECT cyl, am FROM mtcars")
head(df)
cyl am
1 6 1
2 6 1
3 4 1
4 6 0
5 8 0
6 6 0
#Using DISTINCT command
df = sqldf("SELECT DISTINCT cyl, am FROM mtcars")
head(df)
cyl am
1 6 1
2 4 1
3 6 0
4 8 0
5 4 0
6 8 1
-Lets us filter rows based on one or more conditions
-SELECT column_names FROM df_name WHERE condition
-We’ll start with a single condition and then extend to multiple conditions
#Using WHERE command
df = sqldf("SELECT * FROM mtcars WHERE cyl=4")
head(df)
mpg cyl disp hp drat wt qsec vs am gear carb
1 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
2 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
3 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
4 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
5 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
6 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
#Don't have to SELECT columns in where condition
df = sqldf("SELECT mpg, qsec FROM mtcars WHERE cyl=4")
head(df)
mpg qsec
1 22.8 18.61
2 24.4 20.00
3 22.8 22.90
4 32.4 19.47
5 30.4 18.52
6 33.9 19.90
#Using AND within WHERE clause: both conditions have to be true
#for the row to be selected
df = sqldf("SELECT * FROM mtcars WHERE cyl=4 AND qsec < 19")
head(df)
mpg cyl disp hp drat wt qsec vs am gear carb
1 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
2 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
3 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
4 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
5 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
6 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2
#Using AND with an OR also: for OR we need one of the clauses to be true
df = sqldf("SELECT * FROM mtcars WHERE (cyl=4 AND qsec < 19) OR cyl=6")
head(df, 10)
mpg cyl disp hp drat wt qsec vs am gear carb
1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
5 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
6 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
7 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
8 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
10 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
-Lets us aggregate rows that have similar features in specified columns
-SELECT function(column_names) FROM df_name WHERE condition GROUP BY column_name
-The function tells you how the rows will be aggregated: MIN, MAX, AVG, COUNT, STDEV
-We’ll start with a single condition and then extend to multiple conditions
-You don’t have to print out the column you condition on
#COUNT() counts the number of rows. Independent of the data that is in the row.
df = sqldf("SELECT COUNT(*) FROM mtcars GROUP BY cyl")
df
COUNT(*)
1 11
2 7
3 14
#When using GROUP BY we will generally want to alias
df = sqldf("SELECT COUNT(*) AS 'Cyl Counts' FROM mtcars GROUP BY cyl")
df
Cyl Counts
1 11
2 7
3 14
#Now we can see which rows correspond to each of the
#different numbers of cylinders
df = sqldf("SELECT cyl,COUNT(*) FROM mtcars GROUP BY cyl")
df
cyl COUNT(*)
1 4 11
2 6 7
3 8 14
#Get the avg. quarter mile time for automatic versus
#manual cars
df = sqldf("SELECT am,AVG(qsec) FROM mtcars GROUP BY am")
df
am AVG(qsec)
1 0 18.18316
2 1 17.36000
#Get the avg. quarter mile time for automatic versus
#manual cars by number of cylinders
df = sqldf("SELECT cyl, am, AVG(qsec) FROM mtcars GROUP BY cyl, am")
df
cyl am AVG(qsec)
1 4 0 20.97000
2 4 1 18.45000
3 6 0 19.21500
4 6 1 16.32667
5 8 0 17.14250
6 8 1 14.55000
-The WHERE filtering happens before the groups are formed.
#Get the avg. quarter mile time for automatic versus
#manual cars by number of cylinders
df = sqldf("SELECT cyl, am, AVG(qsec) AS Avg_qsec FROM mtcars WHERE
cyl>4 GROUP BY cyl, am")
df
cyl am Avg_qsec
1 6 0 19.21500
2 6 1 16.32667
3 8 0 17.14250
4 8 1 14.55000
#Get the avg. quarter mile time for automatic versus
#manual cars by number of cylinders
df = sqldf("SELECT cyl, am, AVG(qsec) FROM mtcars WHERE
(cyl>4 OR qsec>15) GROUP BY cyl, am")
df
cyl am AVG(qsec)
1 4 0 20.97000
2 4 1 18.45000
3 6 0 19.21500
4 6 1 16.32667
5 8 0 17.14250
6 8 1 14.55000
#Read in grades.csv
gradesFulldf =read.csv("Grades.csv")
head(gradesFulldf)
X Previous_Part Participation1 Mini_Exam1 Mini_Exam2 Participation2
1 1 32 1 19.5 20 1
2 2 32 1 20.0 16 1
3 3 30 1 19.0 19 1
4 4 31 1 22.0 13 1
5 5 30 1 19.0 17 1
6 6 31 1 19.0 19 1
Mini_Exam3 Final Grade partipationPercentage partipationFinal
1 10.0 33.0 A 1 5
2 14.0 32.0 A 1 5
3 10.5 33.0 A- 1 5
4 13.0 34.0 A 1 5
5 12.5 33.5 A 1 5
6 8.0 24.0 B 1 5
MiniOnePercentage MiniOneFinal MiniTwoPercentage MiniTwoFinal
1 0.975 4.875 0.9523810 11.428571
2 1.000 5.000 0.7619048 9.142857
3 0.950 4.750 0.9047619 10.857143
4 1.100 5.500 0.6190476 7.428571
5 0.950 4.750 0.8095238 9.714286
6 0.950 4.750 0.9047619 10.857143
MiniThreePercentage MiniThreeFinal examPercentage examFinal
1 0.8333333 12.500 0.8250 24.750
2 1.1666667 17.500 0.8000 24.000
3 0.8750000 13.125 0.8250 24.750
4 1.0833333 16.250 0.8500 25.500
5 1.0416667 15.625 0.8375 25.125
6 0.6666667 10.000 0.6000 18.000
finalPercentage
1 90.55357
2 92.64286
3 88.48214
4 90.67857
5 90.21429
6 79.60714
#Find the counts of each letter grade given
gradeCounts = sqldf("SELECT COUNT(*) FROM gradesFulldf")
gradeCounts
COUNT(*)
1 153
#Find the counts of each letter grade given
gradeCounts = sqldf("SELECT Grade, COUNT(*) AS Count FROM gradesFulldf GROUP BY Grade")
gradeCounts
Grade Count
1 A 60
2 A+ 2
3 A- 24
4 B 45
5 B+ 16
6 B- 2
7 C+ 4
#What if we want them in the correct order?
gradeCounts[order(gradeCounts$Grade),]
Grade Count
1 A 60
3 A- 24
2 A+ 2
4 B 45
6 B- 2
5 B+ 16
7 C+ 4
#Have to reset the order of the levels using the factor command
gradeCounts$Grade <- factor(gradeCounts$Grade, levels = c("A+", "A", "A-", "B+", "B", "B-", "C+"))
gradeCounts[order(gradeCounts$Grade),]
Grade Count
2 A+ 2
1 A 60
3 A- 24
5 B+ 16
4 B 45
6 B- 2
7 C+ 4
#Use WHERE clause with an AND . Don't need single quotes around A but good habit
AStudents = sqldf("SELECT * FROM gradesFulldf WHERE examPercentage <0.9 AND Grade = 'A' ")
#Get the final percentages of students who got at least 90% on the final
df_goodFinal = sqldf("SELECT finalPercentage FROM gradesFulldf WHERE examPercentage >= 0.9 ")
#Plot these percentages
goodFinal_distribution = ggplot(df_goodFinal, aes(finalPercentage)) +geom_histogram(binwidth = 2) +labs(title ="Percentage Breakdown for Good Finals")
goodFinal_distribution
5.Find the average mini exam scores for those who got a B+,B, and B-
#Get the averages the three types of B
avgMiniB = sqldf("SELECT Grade, AVG(MiniOnePercentage) AS avg_1, AVG(MiniTwoPercentage) AS avg_2, AVG(MiniThreePercentage) AS avg_3 FROM gradesFulldf
WHERE Grade = 'B+' OR Grade = 'B' OR Grade = 'B-' GROUP BY Grade")
avgMiniB
Grade avg_1 avg_2 avg_3
1 B 0.8872222 0.7841270 0.8231481
2 B+ 0.9328125 0.7976190 0.9114583
3 B- 0.5250000 0.6428571 0.5625000
-We can use SQL to manipulate the data for plotting or to do basic calculations.
SELECT and Aliasing
WHERE
GROUP BY