library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.2.1     ✔ readr     2.2.0
## ✔ forcats   1.0.1     ✔ stringr   1.6.0
## ✔ ggplot2   4.0.3     ✔ tibble    3.3.1
## ✔ lubridate 1.9.5     ✔ tidyr     1.3.2
## ✔ purrr     1.2.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(gapminder)

Q1: Vitamin C and tooth growth

#Q1
#• Identify the outcome variable and the explanatory variables.
# - explanatory variable is also known as the independent variable. \\ the outcome variable is the measured effect, the output
# - In this dataset, the explanatory variable is supp (VC or OJ) and dose respectively. The outcome variable is len and a visual pattern respectively. 
#• Classify each variable as continuous or discrete.
# - discrete variables are defined as countable, distinct items; ex: number of cars, no. of students - INTEGERS-GAPS \\ continous variables are defined as any real number; ex: height, weight, skull circumference - floats/doubles
# - discrete variables: supp: OJ and VC \\ continuous variables are len and dose
# 
#• Although dose is stored as a number, it has only three treatment levels. Explain whether you will treat
#it as continuous or discrete in your graph.
# - By the definition of discrete variables, a variable is purely discrete when it only takes separate values with no values in between. This means that such values are generally integers/whole numbers. Because of the existence of .5, this means that such values could exist 1.0 and 2.0, implying a range of values(continuous). 
#• State what pattern you expect to find and why. Should vitamin C promote tooth growth?
# - My assumption is the supplment type will promote tooth growth. This visual pattern then should represent a positive relationship as dosage increases, there is an increase in the tooth length. 


#Compare dosage levels
#Explain why you selected it, and describe the pattern shown by the graph
# - The geometry used was a box plot. It displays extrema, the median, and the 1st and 3rd quartile median values, showing the distributional effects of each dosage on the effected tooth length.
ggplot(data=ToothGrowth, aes(x=dose, y=len, group = dose))+
  geom_boxplot()

#Add delivery method
#I used the function facet_wrap(arg) to visualize both the absorbic acid and orange juice. This method divides the graph into the two categories of supplement easily while maintaining the original x-y axis. Additionally, the data retains the positive relationship, as the dose increases (i.e .5 to 1. and 2.), the tooth length increases as well.  
ggplot(data=ToothGrowth, aes(x=dose, y=len, group = dose))+
  geom_boxplot()+
  facet_wrap(~ToothGrowth$supp)

#verify
#Do the two graphs support the same conclusion? 
# - The two graphs ultimately do support the same conclusion that a high dosage correlates to increased tooth growth length. The difference in delivery method is simply visual. With facet_wrap(), it separates the data by 2 separate graphs while the aes() places the doses adjacent to another. The difference in delivery creates a visual difference.
ggplot(data=ToothGrowth, aes(x=dose, y=len, group = interaction(dose,supp), fill= supp))+
  geom_boxplot()

##Q2 Problem 2: Wealth and life expectancy

#Because people live longer in wealthy countries, economic growth explains differences in life
#expectancy
#• Identify the variables needed to evaluate whether wealth and life expectancy are associated.
# variables needed to evalutate wealth and life expectancy are gdpPercap, life expectancy, and year.
#• Identify the explanatory and outcome variables and classify their types.
# the explanatory variable is gdpPercap and the outcome variable is lifeExp
#• State what visual comparison would provide evidence about the claim.
# A visual comparison that could provide evidence about the claim is a scatter plot
#• Predict the pattern you expect to see.
# I expect to see a positive relationship between gdp per capita and life expectancy. As gdp per capita increases, the life expectancy will increase as well. 



#Examine the overall relationship
#Make a graph showing the relationship and life expectancy. Include the individual
#observations and a smoothed summary.

# - The use of scatter plot has great utility in displaying continous variables gdpPercap and lifeExp respectively. With numerous data points, the scatter plot can be used to find a line of best fit, displaying a concaved downward curve: there is a meterioric increase in life expectancy from 0$ to $15000 gdp per capita, plateauing at approximately $45,000 then gradually declining from $45,000 to $105,000 gdp per capita.
#There is neither a sole positive or negative linear relationship present through the graph. 
#The strength of the relationship is incredibly apparent in the beginning. The line of best fit accurately reflects the cluster of life data points; however, as the graph progresses, the line of best fit's strength regarding the points becomes moderate to weak in its representation of the data. 
# There are some areas of the graph that do not fit pattern. For instance, at approximately (~30,000, 58) and similar points around it, these stray far from the line of best fit. 

ggplot(data=gapminder, aes(x=gdpPercap, y=lifeExp))+
  geom_point()+
  geom_smooth()
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

#Revise the graph so that continents are represented by different colors and each continent has its own
#smoothed summary.
#Explain where the continent mapping must appear in the ggplot code for both the points and smoothers to
#inherit it. What becomes visible in this graph that was hidden in the overall graph?

# - For both the point and smoothers to inherit the colors based on continent, the code must be inputted as an argument in ggplot(aes(argument)). Otherwise, this output can only be achieved by inputting the aes(color) as parameter in both geom_point() and geom_smooth().
# The visualization that was created from the graph was that life expectancy is accumulation of data from 5 continents. The use of color based on continent distinguishes the life expectancy from one another and highlights the max. boundaries of gdpPercap and trends based on continent instead of the overall data set. 


ggplot(data=gapminder, aes(x=gdpPercap, y=lifeExp))+
  geom_point(aes(color=continent))+
  geom_smooth(aes(color=continent))
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

#4. Examine change over time
#Life expectancy observations from different years are pooled together in the previous graphs. Make a line
#graph showing how life expectancy changed over time for each country. Use group = country so that R
#connects observations from the same country, and facet the graph by continent.
#Explain why a line graph is appropriate here. Identify one broad pattern and one important exception or
#source of variation

# A line graph is appropriate here because the data displays numerous life expectancies of countries in their respective continents.The line graph provides a better visualization compared to scatter and box plot that were used previously. Though scatter plot has a line of best fit function, this serves only as a function of data set. With a line graph, not only does it present the raw continuous variable but also of each country. 
# One broad pattern seen through each line graph is that there is a overall positive linear relationship. An exception in this pattern is Asia and Africa, both displaying incredible declines in life expectancy between 1960-1980 and 1980-2000 respectively. 
# A source of variation is that Oceania only displays two countries in its line graph while there are a total of 14 countries(inclusive). All all the other continents sampled countries, Oceania has the lowest by count and proportion. 

ggplot(data=gapminder, aes(x=year, y=lifeExp))+
  geom_line(aes(group=country))+
  facet_wrap(~gapminder$continent)

#5. Evaluate the claim
#Return to the original claim. Write a short paragraph that distinguishes between:
#• what the graphs show;
#• what additional pattern became visible after accounting visually for continent and time; and
#• what you conclude overall about the original claim

#Because people live longer in wealthy countries, economic growth explains differences in life
#expectancy
#In general, the graph presents a positive linear relationship between gdp per capita and life expectancy. 
#However, as the data was parsed by country, continent, and time, there was a variance from this upward trend. For instance, though the original scatter plot of the entire data set showcased a positive trend between gdp per capita and life expectancy, at a closer look with a line graph by country and year, life expectancy actually dropped during certain periods for countries. 
#Ultimately, though gdp per capita and life expectancy are usually associated with one another(higher gdp per captia means great life expectancy), this correlation does not mean causation. Higher gdp may mean greater opportuntiy to access healthcare, to obtain an education but it does not directly mean a higher life expectancy. 

#Q3: Counts and proportions answer different questions

You can also embed plots, for example:

#1. Start with counts
#make a side-by-side bar chart showing the number of diamonds in each cut category, separated by color grade.
#What question does this graph answer? Explain why raw counts may not answer the manager’s question if
#the dataset contains different total numbers of diamonds from each color grade

# - The graph gives a general answer to quantity of "fair" to "ideal" diamond cuts. However, it is unclear whether if each category has the 'same mixture'/proportionately equal based off of total count of diamonds in each category. 
# The bar graph utlimately does not answer the manager's question because of the 5 categories: there totals drastically differ. To answer his question, to find the "same mixture," it must be achieved through comparing the if the color is proportionately the same in each cut category.

# - The numerator should contain the count of the specified color in that cut. This is divided by the total of all the colors in that cut. 

ggplot(data=diamonds, aes(x=cut, fill = color))+
  geom_bar(position = "dodge")

#2
#Make a second bar chart using percentages rather than counts. Each color grade should have its own denomi
#-nator, so that the graph compares the distribution of cuts within each color grade. Use the after_stat(prop)
#and group syntax introduced in lecture.
#Explain in words what belongs in the numerator and denominator of each percentage.
ggplot(data = diamonds, aes(x = cut, fill = color)) +
  geom_bar(aes(y = after_stat(prop), group = color), position = "dodge")

#3. Compare and conclude
#Compare the count and percentage graphs:
# Give one conclusion supported by the count graph.
#• Give one different conclusion supported by the percentage graph.
#• Explain which graph better answers the manager’s question and why
#Does our inventory have the same mixture of diamond cuts within every color grade?

#In the count graph, 'Ideal G' is the most common cut of diamond. In general, it seems "ideal" by count has the most inventory compared to other cuts. 
# Though J by the count graph is not represented by quantity in each type of cut, it is actually proportionately represented in the 'fair' to 'premium' bat graphs, either approximately proportional to the other cuts or even greater. 
#The percentage graph better answers the manager's question. The count graph simply gives the raw number for each cut and color of diamond. This does not directly answer if the diamond cuts have the same mixture within every color grade. On the other hand, the percentage graph compares the color of the diamond to the total cut and color of diamonds, displaying the shape of the cut of diamond distribution per color like the manager asked.