22 |
23 | [](https://github.com/AammarTufail)
24 | [](https://www.kaggle.com/muhammadaammartufail)
25 | [](https://www.linkedin.com/in/dr-muhammad-aammar-tufail-02471213b/)
26 |
27 | [](https://www.youtube.com/@codanics)
28 | [](https://www.facebook.com/aammar.tufail)
29 | [](https://www.tiktok.com/@draammar)
30 |
31 | [](https://twitter.com/aammar_tufail)
32 | [](https://www.instagram.com/aammartufail/)
33 | [](mailto:aammar@codanics.com)
34 |
35 |
36 | For any query
37 |
38 | contact: info@codanics.com
39 |
40 | ---
41 | ---
42 |
43 | ## **Our youtube channel:**
44 | [Our Youtube Channel](http://www.youtube.com/watch?v=omk5b1m2h38)
45 |
46 | Our Daily Lectures are available on our youtube channel. Please subscribe to our channel and find all lectures on youtube as well. [Here is the link playlist for this course](https://youtu.be/v54SksXk9Uk)
47 |
48 | visit our website for more details:
49 | [www.codanics.com](https://www.codanics.com/)
50 | ---
--------------------------------------------------------------------------------
/01_basics/09_distributions.R:
--------------------------------------------------------------------------------
1 | # library packages -----
2 | library(tidyverse)
3 | library(readxl)
4 | df <- read_excel("data/titanic.xlsx")
5 | View(df)
6 |
7 | # draw a histogram
8 | hist(df$age)
9 |
10 | # draw a histogram with ggplot2 having 10 bins
11 | ggplot(df, aes(x = age)) + geom_histogram(bins = 20) +
12 | theme_classic()
13 |
14 | mean(df$age, na.rm = TRUE)
15 | median(df$age, na.rm = TRUE)
16 |
17 |
18 | A <- c(2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 21, 34,100,500)
19 | median(A)
20 |
21 | ## Data Distributions ------
22 | # Normal Distribution
23 | hist(df$age)
24 | shapiro.test(df$age)
25 | hist(df$fare)
26 | shapiro.test(df$fare)
27 | ggplot(df, aes(x = age)) + geom_histogram(bins = 50)
28 | ggplot(df, aes(x = fare)) + geom_histogram(bins = 50)
29 |
30 | # null hypothesis of shapiro wilk test
31 | # H0: data is normally distributed if P > 0.05, 95% confidence level
32 | # H1: data is not normally distributed if P < 0.05, 95% confidence level
33 |
34 |
35 | # do a shapiro wilk test on age and print the results based on values using print fucntion
36 | x <- df$age
37 | if (shapiro.test(x)$p.value > 0.05) {
38 | print("Data is normally distributed")
39 | } else {
40 | print("Data is not normally distributed")
41 | }
42 |
43 | # kurtosis and skewness
44 | # assignment find skewness and kurtosis of age and fare
45 |
46 | # density plot of age
47 | ggplot(df, aes(x = age)) + geom_density() + theme_classic()
48 |
49 | # Why can't we do the same with categorical data
50 | ggplot(df, aes(x = class)) + geom_histogram() + theme_classic()
51 | hist(df$class)
52 |
53 | # count plot of class using ggplot2
54 | ggplot(df, aes(x = class)) + geom_bar()
55 |
56 | ggplot(df, aes(x = class, y = age)) + geom_bar(stat = "identity")
57 | ?geom_bar
58 |
59 | # calculate mean and SD of age and then make a plot with sex
60 | df %>%
61 | group_by(sex) %>%
62 | summarise(mean_age = mean(age, na.rm = TRUE), sd_age = sd(age, na.rm = TRUE))
63 |
64 | df %>%
65 | filter(sex == "female") %>%
66 | ggplot(aes(x = age)) + geom_histogram(bins = 50) + theme_classic()
67 |
68 |
69 |
70 | means <- df %>%
71 | group_by(sex) %>%
72 | summarise(mean_age = mean(age, na.rm = TRUE), sd_age = sd(age, na.rm = TRUE))
73 |
74 | ggplot(means, aes(x = sex, y = mean_age)) + geom_bar(stat = "identity") + theme_classic()
75 |
76 |
77 |
78 | # find kurtosis of age
79 | install.packages("moments")
80 | library(moments)
81 | kurtosis(df$age, na.rm = TRUE)
82 | skewness(df$age, na.rm = TRUE)
83 | #fare
84 | kurtosis(df$fare, na.rm = TRUE)
85 | skewness(df$fare, na.rm = TRUE)
86 |
87 |
88 |
89 |
90 |
--------------------------------------------------------------------------------
/01_basics/.Rproj.user/3E742B1C/sources/prop/INDEX:
--------------------------------------------------------------------------------
1 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F00_app.R="6E847884"
2 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F01_basics_in_r.R="E148D84B"
3 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F02_packages_in_r.R="E6EC1E7F"
4 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F03_packages_and_functions.R="76B8F4BC"
5 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F04_auto_data_viz.R="F8479917"
6 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F05_import_data_in_r.R="DB53F96A"
7 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F06_data_transformation.R="3C43C157"
8 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F07_data_handling.R="F56104EB"
9 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F08_missing_values.R="6385D67F"
10 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F09_distributions.R="83B87B57"
11 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F09_kurtosis_skewness.Rmd="52277FB0"
12 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F09_kurtosis_skewness.tex="ABB673A4"
13 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F09_missing_value_imputation_with_mode.R="FED7A754"
14 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F10_thirty_basic_commands_in_R.R="92ECF44F"
15 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2F11_interactive_plots.R="1FD84A30"
16 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2Fapp.R="4EBE599D"
17 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2Fdata%2FBOD_test.tsv="5F668064"
18 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2Fdata%2Ffirst_15_days_of_sept.csv="3DBF7087"
19 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2Fdata%2Fmissing_values.csv="73072AA0"
20 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2Fdata%2Ftitanic.csv="AF90714C"
21 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2Fperplexity_app.R="04BE7D04"
22 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2Fsample_template.R="92323A8C"
23 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F01_basics%2Fshiny_app_data_Extraction.R="9D196B93"
24 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F02_plotting%2F01_plots_from_slr.R="3F4EFEAC"
25 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F02_plotting%2F02_pie_chart.R="3AB48518"
26 | C%3A%2FUsers%2Faammar%2FOneDrive%2F00_SWMP%2F03_r_training%2F02_plotting%2F03_count_plot.R="C27A5C72"
27 |
--------------------------------------------------------------------------------
/01_basics/03_packages_and_functions.R:
--------------------------------------------------------------------------------
1 | ## 1. Packages for Data Loading and data writing ----
2 | install.packages("readxl")
3 | install.packages("readr")
4 | install.packages("openxlsx")
5 | install.packages("writexl")
6 | install.packages("writexls")
7 |
8 | ## 2. Packages for Data Manipulation or Data Wrangling/Handling ----
9 | install.packages("dplyr")
10 | ?base::Logic
11 | ?Comparison
12 | ?base::Arithmetic
13 |
14 | install.packages("tidyverse")
15 | library(tidyverse)
16 |
17 | # lubridate
18 | install.packages("lubridate")
19 |
20 | ## 3. Packages for Data Visualization ----
21 | install.packages("ggplot2")
22 | library(ggplot2)
23 |
24 | # example of ggplot2
25 | # load data
26 | data(mpg)
27 |
28 | # plot
29 | ggplot(data = mpg, # data
30 | aes(x= manufacturer, y = cty)) + # aesthetics
31 | geom_point() # geometry
32 |
33 | # plotly
34 | install.packages("plotly")
35 | library(plotly)
36 | plot_ly(midwest, x = ~percollege, color = ~state, type = "box")
37 |
38 | plot_ly(data = mpg, x = ~manufacturer, y = ~cty, type = "scatter", mode = "markers")
39 |
40 | # gganimate
41 | install.packages("gganimate")
42 | library(gganimate)
43 |
44 | ## ggpubr
45 | install.packages("ggpubr")
46 | library(ggpubr)
47 |
48 | # heatmaply
49 | install.packages("heatmaply")
50 | # d3heatmap
51 | install.packages("d3heatmap")
52 |
53 | #rgl
54 | install.packages("rgl") #3D plots
55 |
56 | #leaflet
57 | install.packages("leaflet") #maps
58 |
59 | #dygraphs
60 | install.packages("dygraphs") #time series
61 |
62 | ## 4. Packages for Color pallets ----
63 | install.packages("RColorBrewer")
64 | library(RColorBrewer)
65 |
66 |
67 | ## 5. Packages for statistics and Machine Learning ----
68 |
69 | # tidymodels
70 | install.packages("tidymodels")
71 |
72 | # car
73 |
74 | install.packages("car")
75 |
76 | #lme4/nlme
77 | install.packages("lme4")
78 |
79 | # multcomp
80 | install.packages("multcomp")
81 |
82 | # vcd
83 | install.packages("vcd") # categorical data
84 |
85 | # survival
86 | install.packages("survival") # survival analysis
87 |
88 | # agricolae
89 | install.packages("agricolae") # agricolae
90 |
91 | # caret
92 | install.packages("caret") # machine learning
93 |
94 | #randomForest
95 | install.packages("randomForest") # random forest
96 |
97 |
98 |
99 | ## 6. Packages for Reporting ----
100 |
101 | # rmarkdown
102 | install.packages("rmarkdown")
103 |
104 | #shiny
105 | install.packages("shiny")
106 |
107 | ## 7. Packages for Systematic Review and Meta-analysis ----
108 |
109 | #tidyverse
110 | install.packages("tidyverse")
111 |
112 | #meta
113 | install.packages("meta")
114 |
115 | #metafor
116 | install.packages("metafor")
117 |
118 | # dmetar
119 | install.packages("devtools")
120 | devtools::install_github("MathiasHarrer/dmetar")
121 |
122 | #openxlsx
123 | install.packages("openxlsx")
124 |
125 |
126 |
127 | ### 7.1 Additional Meta-analysis Packages----
128 | #metagear
129 | install.packages("BiocManager");
130 | BiocManager::install("EBImage")
131 | install.packages("metagear_0.7.tar.gz", repos = "http://cran.us.r-project.org", type = "source", dependencies = TRUE)
132 | library(metagear)
133 |
134 | #juicr
135 | install.packages("XML")
136 | install.packages("BiocManager");
137 | BiocManager::install("EBImage")
138 | install.packages("juicr_0.1.tar.gz", repos = "http://cran.us.r-project.org", type = "source", dependencies = TRUE)
139 | library(juicr)
140 | #switchboard
141 | install.packages("switchboard")
142 |
--------------------------------------------------------------------------------
/01_basics/01_basics_in_r.R:
--------------------------------------------------------------------------------
1 | ## Basic Arithmetic operations----
2 | # we added 2 in 3
3 | 2+3
4 | # we will add x in y
5 | x = 2
6 | y = 3
7 | x+y
8 | y-x
9 | x-y
10 | x*y
11 | x^y
12 | 2^3
13 | 2*2*2
14 | x/3
15 |
16 |
17 | ### Some other operators----
18 | a <- 2
19 | b <- 4+2
20 | b
21 | print(b)
22 | a*2+b-(3^2)/(10*300)
23 |
24 |
25 | ## Data structures in R----
26 | ## 1. Vectors
27 | # Vectors are one dimensional arrays that can hold numeric data, character data, or logical data.
28 | # The elements in a vector all have the same data type.
29 | # Vectors are created using the c() function. You place the vector elements separated by a comma between the c() function's parentheses.
30 |
31 | # Numeric vector
32 | num_vector <- c(1, 2, 3, 4, 5)
33 | num_vector
34 |
35 | # Character vector
36 | char_vector <- c("a", "b", "c", "d", "e")
37 | char_vector
38 |
39 | # Logical vector
40 | logical_vector <- c(TRUE, FALSE, TRUE, FALSE, TRUE)
41 | logical_vector
42 |
43 | # Dataframes in R----
44 | # Dataframes are two-dimensional arrays that can hold numeric data, character data, or logical data.
45 | # They are similar to matrices but can have columns of different data types.
46 | # Columns of a dataframe can be of different types.
47 | # Dataframes are created using the data.frame() function.
48 |
49 | # Create a dataframe
50 | df <- data.frame(
51 | num = c(1, 2, 3, 4, 5),
52 | char = c("a", "b", "c", "d", "e"),
53 | logical = c(TRUE, FALSE, TRUE, FALSE, TRUE),
54 | num2 = c(12,14,16,18,20)
55 | )
56 | df
57 | View(df)
58 |
59 |
60 | # Matrix in R ----
61 | # Matrices are two-dimensional arrays that can hold numeric data, character data, or logical data.
62 | # They are similar to vectors but can have rows and columns.
63 | # Matrices are created using the matrix() function.
64 |
65 | # Create a matrix
66 | mat <- matrix(
67 | c(1, 2, 3, 4, 5, 6),
68 | nrow = 2,
69 | ncol = 3
70 | )
71 | mat
72 | View(mat)
73 |
74 |
75 |
76 |
77 |
78 | ## Arrays in R----
79 | # Arrays are similar to matrices but can have more than two dimensions.
80 | # Arrays are created using the array() function.
81 |
82 | # Create an array
83 | arr <- array(
84 | c(1, 2, 3, 4, 5, 6, 7, 8),
85 | dim = c(2, 2, 2)
86 | )
87 | arr
88 |
89 | # List in R----
90 | # Lists are the R objects which contain elements of different types
91 | # like − numbers, strings, vectors and another list inside it.
92 | # A list can also contain a matrix or a function as its elements.
93 | # List is created using list() function.
94 |
95 | # Create a list
96 | list_data <- list(
97 | num = c(1, 2, 3, 4, 5),
98 | char = c("a", "b", "c", "d", "e"),
99 | logical = c(TRUE, FALSE, TRUE, FALSE, TRUE)
100 | )
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | #3 Seq function in R ---
110 | # The seq() function is used to generate sequences in R.
111 | # The seq() function generates a sequence of numbers from a specified range.
112 | # The seq() function takes three arguments: from, to, and by.
113 |
114 | # Generate a sequence from 1 to 10
115 | seq(1, 10)
116 | seq(from=1, to=10)
117 | seq(1, 10, by = 1)
118 | seq(1, 10, by = 2)
119 | seq(0, 10, by = 2)
120 | seq(0, 10, by = 2.5)
121 | seq(5, 10, by = 1.5)
122 | seq(5, 1000000000000, by = 15000)
123 |
124 | # length.out argument
125 | seq(1, 10, length.out = 20)
126 |
127 | # along.with argument
128 | vec <- c(10,20,30,40, 50)
129 | seq(along.with = vec)
130 |
131 |
132 | # descending sequence
133 | seq(10, 1, by = -1)
134 |
135 | seq(1,10, 2)
136 |
--------------------------------------------------------------------------------
/01_basics/10_thirty_basic_commands_in_R.R:
--------------------------------------------------------------------------------
1 | # library packages -----
2 | library(readxl)
3 | df <- read_excel("data/titanic.xlsx")
4 |
5 | # 1
6 | View(df) # to view the dataframe
7 |
8 | #2
9 | str(df) # to see the structure of the dataframe
10 |
11 | #3
12 | summary(df) # to see the summary of the dataframe
13 |
14 | #4
15 | dim(df) # to see the dimensions of the dataframe
16 |
17 | #5
18 | head(df) # to see the first 6 rows of the dataframe
19 |
20 | #6
21 | tail(df) # to see the last 6 rows of the dataframe
22 |
23 | #7
24 | nrow(df) # to see the number of rows in the dataframe
25 |
26 | #8
27 | ncol(df) # to see the number of columns in the dataframe
28 |
29 | #9
30 | colnames(df) # to see the column names of the dataframe
31 | row.names(df) # to see the row names of the dataframe
32 |
33 | #10
34 | class(df$pclass) # to see the class of the dataframe
35 | class(df$sex) # to see the class of the dataframe
36 | sapply(df, class) # to see the class of each column in the dataframe
37 |
38 | #11
39 | levels(df$pclass)
40 | # make pclass as factor
41 | df$pclass <- as.factor(df$pclass)
42 |
43 | #12
44 | is.na(df) # to see the missing values in the dataframe
45 | sum(is.na(df)) # to see the total missing values in the dataframe)
46 | sum(is.na(df$age)) # to see the total missing values in the age column
47 |
48 | #13
49 | colSums(is.na(df)) # to see the missing values in each column of the dataframe
50 |
51 | #14
52 | duplicated(df) # to see the duplicated rows in the dataframe
53 |
54 | #15
55 | sum(duplicated(df)) # to see the total duplicated rows in the dataframe
56 |
57 | #16
58 | df_first_class <- subset(df, class == "First") # to subset the dataframe based on the condition
59 |
60 | #17
61 | sort(df$age) # to sort the age column in the dataframe
62 | sort(df$pclass)
63 | min(df$age, na.rm = TRUE) # to see the minimum value in the age column
64 | max(df$age, na.rm = TRUE) # to see the maximum value in the age column
65 |
66 | #18
67 | df[order(df$age),] # to sort the dataframe based on the age column
68 | df_ordered_pclass <- df[order(df$pclass), ]
69 |
70 | #19
71 | mean(df$age, na.rm = TRUE) # to see the mean of the age column
72 |
73 | #20
74 | median(df$age, na.rm = TRUE) # to see the median of the age column
75 |
76 | #21
77 | sd(df$age, na.rm = TRUE) # to see the standard deviation of the age column
78 | se <- sd(df$age, na.rm = TRUE)/sqrt(nrow(df)) # to see the standard error of the age column
79 |
80 | #22
81 | quantile(df$age, na.rm = TRUE) # to see the quantiles of the age column
82 | # inter quartile range
83 | IQR(df$age, na.rm = TRUE)
84 |
85 | #23
86 | range(df$age, na.rm = TRUE) # to see the range of the age column
87 |
88 | ### Categorical Variables frequencies
89 | #24
90 | table(df$class) # to see the frequency of each class in the class column
91 | table(df$sex) # to see the frequency
92 | table(df$who) # to see the frequency
93 | table(df$embarked) # to see the frequency
94 |
95 | #25
96 | length(df) # to see the length of the dataframe
97 | length(df$sex) # to see
98 |
99 |
100 | #26
101 | length(unique(df$sex)) # to see the number of unique values in sex
102 | length(unique(df$class)) # to see the number of unique values in
103 | length(unique(df$age))
104 | length(unique(df$embarked))
105 |
106 |
107 | #27
108 | prop.table(table(df$class)) # to see the proportion of each class in the class column
109 | # find percentage of each class
110 | prop.table(table(df$class))*100
111 |
112 | #28
113 | cor(df$age, df$fare, use = "complete.obs") # to see the correlation between age and fare
114 | cor(df$age, df$fare, use = "pairwise.complete.obs") # to see the correlation between age and fare
115 | #29
116 | hist(df$age) # to see the histogram of the age column
117 |
118 | #30
119 | boxplot(df$age) # to see the boxplot of the age column
120 |
121 | plot(df)
122 |
123 |
--------------------------------------------------------------------------------
/01_basics/data/iris.csv:
--------------------------------------------------------------------------------
1 | "","Sepal.Length","Sepal.Width","Petal.Length","Petal.Width","Species"
2 | "1",5.1,3.5,1.4,0.2,"setosa"
3 | "2",4.9,3,1.4,0.2,"setosa"
4 | "3",4.7,3.2,1.3,0.2,"setosa"
5 | "4",4.6,3.1,1.5,0.2,"setosa"
6 | "5",5,3.6,1.4,0.2,"setosa"
7 | "6",5.4,3.9,1.7,0.4,"setosa"
8 | "7",4.6,3.4,1.4,0.3,"setosa"
9 | "8",5,3.4,1.5,0.2,"setosa"
10 | "9",4.4,2.9,1.4,0.2,"setosa"
11 | "10",4.9,3.1,1.5,0.1,"setosa"
12 | "11",5.4,3.7,1.5,0.2,"setosa"
13 | "12",4.8,3.4,1.6,0.2,"setosa"
14 | "13",4.8,3,1.4,0.1,"setosa"
15 | "14",4.3,3,1.1,0.1,"setosa"
16 | "15",5.8,4,1.2,0.2,"setosa"
17 | "16",5.7,4.4,1.5,0.4,"setosa"
18 | "17",5.4,3.9,1.3,0.4,"setosa"
19 | "18",5.1,3.5,1.4,0.3,"setosa"
20 | "19",5.7,3.8,1.7,0.3,"setosa"
21 | "20",5.1,3.8,1.5,0.3,"setosa"
22 | "21",5.4,3.4,1.7,0.2,"setosa"
23 | "22",5.1,3.7,1.5,0.4,"setosa"
24 | "23",4.6,3.6,1,0.2,"setosa"
25 | "24",5.1,3.3,1.7,0.5,"setosa"
26 | "25",4.8,3.4,1.9,0.2,"setosa"
27 | "26",5,3,1.6,0.2,"setosa"
28 | "27",5,3.4,1.6,0.4,"setosa"
29 | "28",5.2,3.5,1.5,0.2,"setosa"
30 | "29",5.2,3.4,1.4,0.2,"setosa"
31 | "30",4.7,3.2,1.6,0.2,"setosa"
32 | "31",4.8,3.1,1.6,0.2,"setosa"
33 | "32",5.4,3.4,1.5,0.4,"setosa"
34 | "33",5.2,4.1,1.5,0.1,"setosa"
35 | "34",5.5,4.2,1.4,0.2,"setosa"
36 | "35",4.9,3.1,1.5,0.2,"setosa"
37 | "36",5,3.2,1.2,0.2,"setosa"
38 | "37",5.5,3.5,1.3,0.2,"setosa"
39 | "38",4.9,3.6,1.4,0.1,"setosa"
40 | "39",4.4,3,1.3,0.2,"setosa"
41 | "40",5.1,3.4,1.5,0.2,"setosa"
42 | "41",5,3.5,1.3,0.3,"setosa"
43 | "42",4.5,2.3,1.3,0.3,"setosa"
44 | "43",4.4,3.2,1.3,0.2,"setosa"
45 | "44",5,3.5,1.6,0.6,"setosa"
46 | "45",5.1,3.8,1.9,0.4,"setosa"
47 | "46",4.8,3,1.4,0.3,"setosa"
48 | "47",5.1,3.8,1.6,0.2,"setosa"
49 | "48",4.6,3.2,1.4,0.2,"setosa"
50 | "49",5.3,3.7,1.5,0.2,"setosa"
51 | "50",5,3.3,1.4,0.2,"setosa"
52 | "51",7,3.2,4.7,1.4,"versicolor"
53 | "52",6.4,3.2,4.5,1.5,"versicolor"
54 | "53",6.9,3.1,4.9,1.5,"versicolor"
55 | "54",5.5,2.3,4,1.3,"versicolor"
56 | "55",6.5,2.8,4.6,1.5,"versicolor"
57 | "56",5.7,2.8,4.5,1.3,"versicolor"
58 | "57",6.3,3.3,4.7,1.6,"versicolor"
59 | "58",4.9,2.4,3.3,1,"versicolor"
60 | "59",6.6,2.9,4.6,1.3,"versicolor"
61 | "60",5.2,2.7,3.9,1.4,"versicolor"
62 | "61",5,2,3.5,1,"versicolor"
63 | "62",5.9,3,4.2,1.5,"versicolor"
64 | "63",6,2.2,4,1,"versicolor"
65 | "64",6.1,2.9,4.7,1.4,"versicolor"
66 | "65",5.6,2.9,3.6,1.3,"versicolor"
67 | "66",6.7,3.1,4.4,1.4,"versicolor"
68 | "67",5.6,3,4.5,1.5,"versicolor"
69 | "68",5.8,2.7,4.1,1,"versicolor"
70 | "69",6.2,2.2,4.5,1.5,"versicolor"
71 | "70",5.6,2.5,3.9,1.1,"versicolor"
72 | "71",5.9,3.2,4.8,1.8,"versicolor"
73 | "72",6.1,2.8,4,1.3,"versicolor"
74 | "73",6.3,2.5,4.9,1.5,"versicolor"
75 | "74",6.1,2.8,4.7,1.2,"versicolor"
76 | "75",6.4,2.9,4.3,1.3,"versicolor"
77 | "76",6.6,3,4.4,1.4,"versicolor"
78 | "77",6.8,2.8,4.8,1.4,"versicolor"
79 | "78",6.7,3,5,1.7,"versicolor"
80 | "79",6,2.9,4.5,1.5,"versicolor"
81 | "80",5.7,2.6,3.5,1,"versicolor"
82 | "81",5.5,2.4,3.8,1.1,"versicolor"
83 | "82",5.5,2.4,3.7,1,"versicolor"
84 | "83",5.8,2.7,3.9,1.2,"versicolor"
85 | "84",6,2.7,5.1,1.6,"versicolor"
86 | "85",5.4,3,4.5,1.5,"versicolor"
87 | "86",6,3.4,4.5,1.6,"versicolor"
88 | "87",6.7,3.1,4.7,1.5,"versicolor"
89 | "88",6.3,2.3,4.4,1.3,"versicolor"
90 | "89",5.6,3,4.1,1.3,"versicolor"
91 | "90",5.5,2.5,4,1.3,"versicolor"
92 | "91",5.5,2.6,4.4,1.2,"versicolor"
93 | "92",6.1,3,4.6,1.4,"versicolor"
94 | "93",5.8,2.6,4,1.2,"versicolor"
95 | "94",5,2.3,3.3,1,"versicolor"
96 | "95",5.6,2.7,4.2,1.3,"versicolor"
97 | "96",5.7,3,4.2,1.2,"versicolor"
98 | "97",5.7,2.9,4.2,1.3,"versicolor"
99 | "98",6.2,2.9,4.3,1.3,"versicolor"
100 | "99",5.1,2.5,3,1.1,"versicolor"
101 | "100",5.7,2.8,4.1,1.3,"versicolor"
102 | "101",6.3,3.3,6,2.5,"virginica"
103 | "102",5.8,2.7,5.1,1.9,"virginica"
104 | "103",7.1,3,5.9,2.1,"virginica"
105 | "104",6.3,2.9,5.6,1.8,"virginica"
106 | "105",6.5,3,5.8,2.2,"virginica"
107 | "106",7.6,3,6.6,2.1,"virginica"
108 | "107",4.9,2.5,4.5,1.7,"virginica"
109 | "108",7.3,2.9,6.3,1.8,"virginica"
110 | "109",6.7,2.5,5.8,1.8,"virginica"
111 | "110",7.2,3.6,6.1,2.5,"virginica"
112 | "111",6.5,3.2,5.1,2,"virginica"
113 | "112",6.4,2.7,5.3,1.9,"virginica"
114 | "113",6.8,3,5.5,2.1,"virginica"
115 | "114",5.7,2.5,5,2,"virginica"
116 | "115",5.8,2.8,5.1,2.4,"virginica"
117 | "116",6.4,3.2,5.3,2.3,"virginica"
118 | "117",6.5,3,5.5,1.8,"virginica"
119 | "118",7.7,3.8,6.7,2.2,"virginica"
120 | "119",7.7,2.6,6.9,2.3,"virginica"
121 | "120",6,2.2,5,1.5,"virginica"
122 | "121",6.9,3.2,5.7,2.3,"virginica"
123 | "122",5.6,2.8,4.9,2,"virginica"
124 | "123",7.7,2.8,6.7,2,"virginica"
125 | "124",6.3,2.7,4.9,1.8,"virginica"
126 | "125",6.7,3.3,5.7,2.1,"virginica"
127 | "126",7.2,3.2,6,1.8,"virginica"
128 | "127",6.2,2.8,4.8,1.8,"virginica"
129 | "128",6.1,3,4.9,1.8,"virginica"
130 | "129",6.4,2.8,5.6,2.1,"virginica"
131 | "130",7.2,3,5.8,1.6,"virginica"
132 | "131",7.4,2.8,6.1,1.9,"virginica"
133 | "132",7.9,3.8,6.4,2,"virginica"
134 | "133",6.4,2.8,5.6,2.2,"virginica"
135 | "134",6.3,2.8,5.1,1.5,"virginica"
136 | "135",6.1,2.6,5.6,1.4,"virginica"
137 | "136",7.7,3,6.1,2.3,"virginica"
138 | "137",6.3,3.4,5.6,2.4,"virginica"
139 | "138",6.4,3.1,5.5,1.8,"virginica"
140 | "139",6,3,4.8,1.8,"virginica"
141 | "140",6.9,3.1,5.4,2.1,"virginica"
142 | "141",6.7,3.1,5.6,2.4,"virginica"
143 | "142",6.9,3.1,5.1,2.3,"virginica"
144 | "143",5.8,2.7,5.1,1.9,"virginica"
145 | "144",6.8,3.2,5.9,2.3,"virginica"
146 | "145",6.7,3.3,5.7,2.5,"virginica"
147 | "146",6.7,3,5.2,2.3,"virginica"
148 | "147",6.3,2.5,5,1.9,"virginica"
149 | "148",6.5,3,5.2,2,"virginica"
150 | "149",6.2,3.4,5.4,2.3,"virginica"
151 | "150",5.9,3,5.1,1.8,"virginica"
152 |
--------------------------------------------------------------------------------
/02_plotting/plots/01_plot.svg:
--------------------------------------------------------------------------------
1 |
2 |
585 |
--------------------------------------------------------------------------------
/01_basics/.Rhistory:
--------------------------------------------------------------------------------
1 | #19
2 | mean(df$age) # to see the mean of the age column
3 | #20
4 | meadian(df$age, na.rm = TRUE) # to see the median of the age column
5 | #20
6 | median(df$age, na.rm = TRUE) # to see the median of the age column
7 | #21
8 | sd(df$age, na.rm = TRUE) # to see the standard deviation of the age column
9 | se <- sd(df$age, na.rm = TRUE)/sqrt(nrow(df)) # to see the standard error of the age column
10 | #22
11 | quantile(df$age, na.rm = TRUE) # to see the quantiles of the age column
12 | # inter quartile range
13 | IQR(df$age, na.rm = TRUE)
14 | #23
15 | range(df$age, na.rm = TRUE) # to see the range of the age column
16 | #24
17 | table(df$pclass) # to see the frequency of each class in the pclass column
18 | ### Categorical Variables frequencies
19 | #24
20 | table(df$class) # to see the frequency of each class in the pclass column
21 | table(df$sex) # to see the frequency
22 | table(df$who)
23 | #25
24 | length(df) # to see the length of the dataframe
25 | length(df$sex)
26 | length(unique(df$sex)) # to see the number of unique values in sex
27 | length(unique(df$class)) # to see the number of unique values in
28 | length(unique(df$age))
29 | length(unique(df$embarked))
30 | table(df$embarked) # to see the frequency
31 | #27
32 | prop.table(table(df$class)) # to see the proportion of each class in the class column
33 | # find percentage of each class
34 | prop.table(table(df$class))*100
35 | #28
36 | cor(df$age, df$fare) # to see the correlation between age and fare
37 | #28
38 | cor(df$age, df$fare, na.rm = TRUE) # to see the correlation between age and fare
39 | #28
40 | cor(df$age, df$fare, use = "complete.obs") # to see the correlation between age and fare
41 | #29
42 | hist(df$age) # to see the histogram of the age column
43 | #30
44 | boxplot(df$age) # to see the boxplot of the age column
45 | plot(df)
46 | cor(df$age, df$fare, use = "pairwise.complete.obs") # to see the correlation between age and fare
47 | ####----- Plotly for interactive plots -----####
48 | install.packages("plotly")
49 | library(plotly)
50 | library(tidyverse)
51 | # Load the data
52 | data("diamonds")
53 | force(diamonds)
54 | library(readxl)
55 | # Load the data
56 | df <- read_excel("data/titanic.xlsx")
57 | View(df)
58 | colnames(df)
59 | # scatter plot
60 | plot_ly(df, x = ~age, y = ~fare, type = "scatter")
61 | # scatter plot
62 | plot_ly(df, x = ~age, y = ~fare, color = ~sex, type = "scatter")
63 | # scatter plot
64 | plot_ly(df, x = ~age, y = ~fare, color = ~sex, type = "scatter", mode = "markers")
65 | # line plot
66 | plot_ly(df, x = ~age, y = ~fare, color = ~sex, type = "scatter", mode = "lines")
67 | # line plot
68 | plot_ly(df, x = ~pclass, y = ~fare, color = ~sex, type = "scatter", mode = "lines")
69 | # line plot
70 | plot_ly(df, x = ~pclass, y = ~embarked, color = ~sex, type = "scatter", mode = "lines")
71 | # bar plot
72 | plot_ly(df, x = ~pclass, y = ~fare, color = ~sex, type = "bar")
73 | #histogram
74 | plot_ly(df, x = ~age, type = "histogram")
75 | #boxplot
76 | plot_ly(df, x = ~pclass, y = ~fare, color = ~sex, type = "box")
77 | #boxplot
78 | plot_ly(df, y = ~fare, type = "box")
79 | #boxplot
80 | plot_ly(df, x = ~pclass, y = ~fare, type = "box")
81 | #boxplot
82 | plot_ly(df, x = ~pclass, y = ~fare, type = "box", color=~who)
83 | #boxplot
84 | plot_ly(df, x = ~pclass, y = ~fare,color=~who, type = "box")
85 | # scatter plot
86 | plot_ly(df, x = ~age, y = ~fare, color = ~sex, type = "scatter", mode = "markers")
87 | # scatter plot
88 | plot_ly(df, x = ~age, y = ~fare, color = ~sex, type = "scatter", mode = "markers",
89 | size = ~fare
90 | )
91 | # heatmap
92 | plot_ly(df, x = ~pclass, y = ~embarked, z = ~fare, type = "heatmap")
93 | # heatmap
94 | plot_ly(df, x = ~class, y = ~embark_town, z = ~fare, type = "heatmap")
95 | # heatmap
96 | plot_ly(df, x = ~class, y = ~embark_town, z = ~age, type = "heatmap")
97 | # heatmap
98 | plot_ly(df, x = ~class, y = ~embark_town, z = ~sex, type = "heatmap")
99 | # heatmap
100 | plot_ly(df, x = ~class, y = ~embark_town, z = ~pclass, type = "heatmap")
101 | # heatmap
102 | plot_ly(df, x = ~class, y = ~embark_town, z = ~age, type = "heatmap")
103 | # pie chart
104 | plot_ly(df, labels = ~sex, type = "pie")
105 | # pie chart
106 | plot_ly(df, labels = ~class, type = "pie")
107 | # pie chart
108 | plot_ly(df, labels = ~class, type = "pie", values = ~fare)
109 | #bubble chart
110 | plot_ly(df, x = ~age, y = ~fare, color = ~sex, size = ~fare, type = "bubble")
111 | #bubble chart
112 | plot_ly(df, x = ~age, y = ~fare, color = ~sex, type = "bubble")
113 | #bubble chart
114 | plot_ly(df, x = ~age, y = ~fare, color = ~sex, type = "scatter", mode = "markers",
115 | size = ~fare
116 | )
117 | #bubble chart
118 | plot_ly(df, x = ~age, y = ~fare, color = ~sex, type = "scatter", mode = "markers",
119 | size = ~fare * 0.1
120 | )
121 | #bubble chart
122 | plot_ly(df, x = ~age, y = ~fare, color = ~sex, type = "scatter", mode = "markers",
123 | size = ~fare * 0.5
124 | )
125 | #bubble chart
126 | plot_ly(df, x = ~age, y = ~fare, color = ~sex, type = "scatter", mode = "markers",
127 | size = ~fare * 2
128 | )
129 | # violin plot
130 | plot_ly(df, x = ~pclass, y = ~fare, color = ~sex, type = "violin")
131 | # violin plot
132 | plot_ly(df, x = ~pclass, y = ~age, color = ~sex, type = "violin")
133 | # violin plot
134 | plot_ly(df, x = ~pclass, y = ~age, ctype = "violin")
135 | # violin plot
136 | plot_ly(df, x = ~pclass, y = ~age, type = "violin")
137 | # 3D scatter plot
138 | plot_ly(df, x = ~age, y = ~fare, z = ~pclass, color = ~sex, type = "scatter3d", mode = "markers")
139 | install.packages("GWalkR")
140 | install.packages("esquisse")
141 | install.packages("explore")
142 | library(tidyverse)
143 | library(GWalkR)
144 | library(esquisse)
145 | library(explore)
146 | library(readxl)
147 | # Load data -----
148 | df_ghgs <- read_excel("data/GHGs.xlsx")
149 | # Load data -----
150 | df_ghgs <- read_excel("./data/GHGs.xlsx")
151 | pwd
152 | getwd()
153 | setwd("C:/Users/aammar/OneDrive/00_SWMP/03_r_training/02_plotting")
154 | getwd()
155 | # Load data -----
156 | df_ghgs <- read_excel("./data/GHGs.xlsx")
157 | # Load data -----
158 | df_ghgs <- read_excel("data/GHGs.xlsx")
159 | # Explore data -----
160 | gwalkr(df_ghgs)
161 | esquisser()
162 | esquisser(viewer = "browser")
163 | explore(df_ghgs)
164 | library(tidyverse)
165 | library(readxl)
166 | # load data
167 | df <- read_excel("data/GHGs.xlsx")
168 | getwd
169 | getwd()
170 | # load data
171 | df <- read_excel("data/GHGs.xlsx")
172 | # load data
173 | df <- read_excel("data/GHGs.xlsx")
174 | # load data
175 | df <- read_excel("data/GHGs.xlsx")
176 | View(df)
177 | # Step 1: Create a table with the counts of each crop type
178 | crop_counts <- table(data$crop.type)
179 | # Step 1: Create a table with the counts of each crop type
180 | crop_counts <- table(df$crop.type)
181 | crop_counts
182 | nrow(df)
183 | # load data
184 | df <- read_excel("data/GHGs.xlsx")
185 | # Step 1: Create a table with the counts of each crop type
186 | crop_counts <- table(df$crop.type)
187 | crop_counts
188 | nrow(df)
189 | # Step 2: Create the pie chart
190 | pie(
191 | crop_counts,
192 | labels = paste(names(crop_counts), round(prop.table(crop_counts) * 100, 1), "%"),
193 | col = c("#ff9999", "#66b3ff", "#99ff99", "#ffcc99", "#c2c2f0", "#ffb3e6", "#c4e17f"),
194 | main = "Crop Distribution"
195 | )
196 | # use ggplot2 to create the same piechart
197 | df %>%
198 | count(crop.type) %>%
199 | ggplot(aes(x = "", y = n, fill = crop.type)) +
200 | geom_bar(stat = "identity", width = 1) +
201 | coord_polar("y", start = 0) +
202 | theme_void() +
203 | theme(legend.position = "bottom") +
204 | labs(title = "Crop Distribution") +
205 | scale_fill_manual(values = c("#ff9999", "#66b3ff", "#99ff99", "#ffcc99", "#c2c2f0", "#ffb3e6", "#c4e17f"))
206 | # use ggplot2 to create the same piechart
207 | df %>%
208 | count(crop.type) %>%
209 | ggplot(aes(x = "", y = n, fill = crop.type)) +
210 | geom_bar(stat = "identity", width = 1) +
211 | coord_polar("y", start = 0) +
212 | theme_void() +
213 | theme(legend.position = "bottom") +
214 | labs(title = "Crop Distribution") +
215 | scale_fill_manual(values = c("#ff9999", "#66b3ff", "#99ff99", "#ffcc99", "#c2c2f0", "#ffb3e6", "#c4e17f", "red"))
216 | # use ggplot2 to create the same piechart
217 | df %>%
218 | count(crop.type) %>%
219 | ggplot(aes(x = "", y = n, fill = crop.type)) +
220 | geom_bar(stat = "identity", width = 1) +
221 | coord_polar("y", start = 0) +
222 | theme_void() +
223 | theme(legend.position = "bottom") +
224 | labs(title = "Crop Distribution")
225 | # use ggplot2 to create the same piechart
226 | df %>%
227 | count(crop.type) %>%
228 | ggplot(aes(x = "", y = n, fill = crop.type)) +
229 | geom_bar(stat = "identity", width = 1) +
230 | coord_polar("y", start = 0) +
231 | theme_void()
232 | # use ggplot2 to create the same piechart
233 | df %>%
234 | count(crop.type) %>%
235 | ggplot(aes(x = "", y = n, fill = crop.type)) +
236 | geom_bar(stat = "identity", width = 1)
237 | # use ggplot2 to create the same piechart
238 | df %>%
239 | count(crop.type) %>%
240 | ggplot(aes(x = "", y = n, fill = crop.type)) +
241 | geom_bar(stat = "identity", width = 1) +
242 | coord_polar("y", start = 0) +
243 | theme_void()
244 | # use ggplot2 to create the same piechart
245 | df %>%
246 | count(crop.type)
247 | ## libraries
248 | library(tidyverse)
249 | library(readxl)
250 | # load data
251 | df <- read_excel("data/GHGs.xlsx")
252 | # create a piechart of the GHGs$crop_type
253 | # Assuming your data is already in a dataframe named 'data' with a column 'crop.type'
254 | # Step 1: Create a table with the counts of each crop type
255 | crop_counts <- table(df$crop.type)
256 | crop_counts
257 | nrow(df)
258 | # Step 2: Create the pie chart
259 | pie(
260 | crop_counts,
261 | labels = paste(names(crop_counts), round(prop.table(crop_counts) * 100, 1), "%"),
262 | col = c("#ff9999", "#66b3ff", "#99ff99", "#ffcc99", "#c2c2f0", "#ffb3e6", "#c4e17f"),
263 | main = "Crop Distribution"
264 | )
265 | # use ggplot2 to create the same piechart
266 | df %>%
267 | count(crop.type)
268 | df %>%
269 | count(crop.type) %>%
270 | ggplot(aes(x = "", y = n, fill = crop.type)) +
271 | geom_bar(stat = "identity", width = 1) +
272 | coord_polar("y", start = 0) +
273 | theme_void()
274 | # use ggplot2 to create the same piechart
275 | df %>%
276 | count(crop.type)
277 | ## libraries
278 | library(tidyverse)
279 | library(readxl)
280 | # load data
281 | df <- read_excel("data/GHGs.xlsx")
282 | # count plot in ggplot2
283 | ggplot(data = df, aes(x="crop.type")) + geom_bar()
284 | # count plot in ggplot2
285 | ggplot(data = df, aes(x="crop.type")) + geom_bar(stat = "identity")
286 | # count plot in ggplot2
287 | ggplot(data = df, aes(x=crop.type)) + geom_bar(stat = "identity")
288 | # count plot in ggplot2
289 | ggplot(data = df, aes(x=crop.type, y = df$crop.type)) + geom_bar(stat = "identity")
290 | # count plot in ggplot2
291 | ggplot(data = df, aes(x=crop.type, y = df$study.id)) + geom_bar(stat = "identity")
292 | df %>%
293 | group_by(crop.type) %>%
294 | summarise(counts = n())
295 | df %>%
296 | group_by(crop.type) %>%
297 | summarise(counts = n()) %>%
298 | ggplot(aes(crop.type, counts)) + geom_bar(stat = "identity")
299 | df %>%
300 | group_by(crop.type) %>%
301 | summarise(counts = n()) %>%
302 | ggplot(aes(crop.type, counts)) + geom_bar(stat = "identity") +
303 | geom_tile("Count plot of Crop Type")
304 | df %>%
305 | group_by(crop.type) %>%
306 | summarise(counts = n()) %>%
307 | ggplot(aes(crop.type, counts)) + geom_bar(stat = "identity") +
308 | title("X")
309 | ?ggplot
310 | df %>%
311 | group_by(crop.type) %>%
312 | summarise(counts = n()) %>%
313 | ggplot(aes(crop.type, counts)) + geom_bar(stat = "identity") +
314 | xlab("Crop Type")
315 | df %>%
316 | group_by(crop.type) %>%
317 | summarise(counts = n()) %>%
318 | ggplot(aes(crop.type, counts)) + geom_bar(stat = "identity") +
319 | xlab("Crop Type") + ylab("Number of Observations")
320 | df %>%
321 | group_by(crop.type) %>%
322 | summarise(counts = n()) %>%
323 | ggplot(aes(crop.type, counts, color = crop.type)) + geom_bar(stat = "identity") +
324 | xlab("Crop Type") + ylab("Number of Observations")
325 | df %>%
326 | group_by(crop.type) %>%
327 | summarise(counts = n()) %>%
328 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
329 | xlab("Crop Type") + ylab("Number of Observations")
330 | df %>%
331 | group_by(crop.type) %>%
332 | summarise(counts = n()) %>%
333 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
334 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic()
335 | df %>%
336 | group_by(crop.type) %>%
337 | summarise(counts = n()) %>%
338 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
339 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
340 | scale_fill_brewer(palette="Dark2")
341 | df %>%
342 | group_by(crop.type) %>%
343 | summarise(counts = n()) %>%
344 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
345 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
346 | scale_fill_brewer(palette="reds")
347 | df %>%
348 | group_by(crop.type) %>%
349 | summarise(counts = n()) %>%
350 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
351 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
352 | scale_fill_brewer(palette="Reds")
353 | df %>%
354 | group_by(crop.type) %>%
355 | summarise(counts = n()) %>%
356 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
357 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
358 | scale_fill_brewer(palette="Accent")
359 | df %>%
360 | group_by(crop.type) %>%
361 | summarise(counts = n()) %>%
362 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
363 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
364 | scale_fill_brewer(palette="Paired")
365 | df %>%
366 | group_by(crop.type) %>%
367 | summarise(counts = n()) %>%
368 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
369 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
370 | # scale_fill_brewer(palette="Paired") +
371 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9"))
372 | df %>%
373 | group_by(crop.type) %>%
374 | summarise(counts = n()) %>%
375 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
376 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
377 | # scale_fill_brewer(palette="Paired") +
378 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "red", "blue", "green", "orange"))
379 | df %>%
380 | group_by(crop.type) %>%
381 | summarise(counts = n()) %>%
382 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
383 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
384 | # scale_fill_brewer(palette="Paired") +
385 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"))
386 | df %>%
387 | group_by(crop.type) %>%
388 | summarise(counts = n()) %>%
389 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
390 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
391 | # scale_fill_brewer(palette="Paired") +
392 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"))+
393 | ggsave("plot.png", scale=1, height = 8, width = 6)
394 | df %>%
395 | group_by(crop.type) %>%
396 | summarise(counts = n()) %>%
397 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
398 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
399 | # scale_fill_brewer(palette="Paired") +
400 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"))+
401 | ggsave("plot.png", scale=1, height = 8, width = 6, dpi = 300)
402 | df %>%
403 | group_by(crop.type) %>%
404 | summarise(counts = n()) %>%
405 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
406 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
407 | # scale_fill_brewer(palette="Paired") +
408 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"))+
409 | ggsave("plot.png", scale=1, height = 8, width = 6, dpi = 600)
410 | df %>%
411 | group_by(crop.type) %>%
412 | summarise(counts = n()) %>%
413 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
414 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
415 | # scale_fill_brewer(palette="Paired") +
416 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"))+
417 | ggsave("plots/01_plot.png", scale=1, height = 8, width = 6, dpi = 300)
418 | p1 <- df %>%
419 | group_by(crop.type) %>%
420 | summarise(counts = n()) %>%
421 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
422 | xlab("Crop Type") + ylab("Number of Observations") + theme_classic() +
423 | # scale_fill_brewer(palette="Paired") +
424 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"))
425 | ggsave(p1, "plots/01_plot.png", scale=1, height = 8, width = 6, dpi = 300)
426 | ?ggsave
427 | ggsave("plots/01_plot.png", plot = p1, scale=1, height = 8, width = 6, dpi = 300)
428 | ggsave("plots/01_plot.svg", plot = p1, scale=1, height = 8, width = 6, dpi = 300)
429 | install.packages("svglite")
430 | library(svglite)
431 | ggsave("plots/01_plot.svg", plot = p1, scale=1, height = 8, width = 6, dpi = 300)
432 | axis.text.x = element_text(angle = 90, hjust = 1) +
433 | p1 <- df %>%
434 | group_by(crop.type) %>%
435 | summarise(counts = n()) %>%
436 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
437 | xlab("Crop Type") + ylab("Number of Observations") +
438 | theme_classic() +
439 | theme(text = element_text(size = 20),
440 | axis.text.x = element_text(angle = 90, hjust = 1)) +
441 | # scale_fill_brewer(palette="Paired") +
442 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"))
443 | p1 <- df %>%
444 | group_by(crop.type) %>%
445 | summarise(counts = n()) %>%
446 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
447 | xlab("Crop Type") + ylab("Number of Observations") +
448 | theme_classic() +
449 | theme(text = element_text(size = 20),
450 | axis.text.x = element_text(angle = 90, hjust = 1))+
451 | # scale_fill_brewer(palette="Paired") +
452 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"))
453 | p1 <- df %>%
454 | group_by(crop.type) %>%
455 | summarise(counts = n()) %>%
456 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
457 | xlab("Crop Type") + ylab("Number of Observations") +
458 | theme_classic() +
459 | theme(text = element_text(size = 20),
460 | axis.text.x = element_text(angle = 90, hjust = 1))+
461 | # scale_fill_brewer(palette="Paired") +
462 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"));p1
463 | p1 <- df %>%
464 | group_by(crop.type) %>%
465 | summarise(counts = n()) %>%
466 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
467 | xlab("Crop Type") + ylab("Number of Observations") +
468 | theme_classic() +
469 | theme(text = element_text(size = 20),
470 | axis.text.x = element_text(angle = 45, hjust = 1))+
471 | # scale_fill_brewer(palette="Paired") +
472 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"));p1
473 | p1 <- df %>%
474 | group_by(crop.type) %>%
475 | summarise(counts = n()) %>%
476 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
477 | xlab("Crop Type") + ylab("Number of Observations") +
478 | theme_classic() +
479 | theme(text = element_text(size = 12),
480 | axis.text.x = element_text(angle = 45, hjust = 1))+
481 | # scale_fill_brewer(palette="Paired") +
482 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"));p1
483 | p1 <- df %>%
484 | group_by(crop.type) %>%
485 | summarise(counts = n()) %>%
486 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
487 | xlab("Crop Type") + ylab("Number of Observations") +
488 | theme_classic() +
489 | theme(text = element_text(size = 25),
490 | axis.text.x = element_text(angle = 45, hjust = 1))+
491 | # scale_fill_brewer(palette="Paired") +
492 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"));p1
493 | p1 <- df %>%
494 | group_by(crop.type) %>%
495 | summarise(counts = n()) %>%
496 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
497 | xlab("Crop Type") + ylab("Number of Observations") +
498 | theme_classic() +
499 | theme(text = element_text(size = 20),
500 | axis.text.x = element_text(angle = 45, hjust = 1))+
501 | # scale_fill_brewer(palette="Paired") +
502 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"));p1
503 | p1 <- df %>%
504 | group_by(crop.type) %>%
505 | summarise(counts = n()) %>%
506 | ggplot(aes(crop.type, counts, fill = crop.type)) + geom_bar(stat = "identity") +
507 | xlab("Crop Type") + ylab("Number of Observations") +
508 | theme_classic() +
509 | theme(text = element_text(size = 14),
510 | axis.text.x = element_text(angle = 45, hjust = 1))+
511 | # scale_fill_brewer(palette="Paired") +
512 | scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#2415ce", "blue", "green", "orange"));p1
513 |
--------------------------------------------------------------------------------
/01_basics/.Rproj.user/3E742B1C/viewer_history/viewhtml42d4235e15da/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/01_basics/.Rproj.user/3E742B1C/viewer_history/viewhtml42d4235e15da/lib/htmlwidgets-1.6.4/htmlwidgets.js:
--------------------------------------------------------------------------------
1 | (function() {
2 | // If window.HTMLWidgets is already defined, then use it; otherwise create a
3 | // new object. This allows preceding code to set options that affect the
4 | // initialization process (though none currently exist).
5 | window.HTMLWidgets = window.HTMLWidgets || {};
6 |
7 | // See if we're running in a viewer pane. If not, we're in a web browser.
8 | var viewerMode = window.HTMLWidgets.viewerMode =
9 | /\bviewer_pane=1\b/.test(window.location);
10 |
11 | // See if we're running in Shiny mode. If not, it's a static document.
12 | // Note that static widgets can appear in both Shiny and static modes, but
13 | // obviously, Shiny widgets can only appear in Shiny apps/documents.
14 | var shinyMode = window.HTMLWidgets.shinyMode =
15 | typeof(window.Shiny) !== "undefined" && !!window.Shiny.outputBindings;
16 |
17 | // We can't count on jQuery being available, so we implement our own
18 | // version if necessary.
19 | function querySelectorAll(scope, selector) {
20 | if (typeof(jQuery) !== "undefined" && scope instanceof jQuery) {
21 | return scope.find(selector);
22 | }
23 | if (scope.querySelectorAll) {
24 | return scope.querySelectorAll(selector);
25 | }
26 | }
27 |
28 | function asArray(value) {
29 | if (value === null)
30 | return [];
31 | if ($.isArray(value))
32 | return value;
33 | return [value];
34 | }
35 |
36 | // Implement jQuery's extend
37 | function extend(target /*, ... */) {
38 | if (arguments.length == 1) {
39 | return target;
40 | }
41 | for (var i = 1; i < arguments.length; i++) {
42 | var source = arguments[i];
43 | for (var prop in source) {
44 | if (source.hasOwnProperty(prop)) {
45 | target[prop] = source[prop];
46 | }
47 | }
48 | }
49 | return target;
50 | }
51 |
52 | // IE8 doesn't support Array.forEach.
53 | function forEach(values, callback, thisArg) {
54 | if (values.forEach) {
55 | values.forEach(callback, thisArg);
56 | } else {
57 | for (var i = 0; i < values.length; i++) {
58 | callback.call(thisArg, values[i], i, values);
59 | }
60 | }
61 | }
62 |
63 | // Replaces the specified method with the return value of funcSource.
64 | //
65 | // Note that funcSource should not BE the new method, it should be a function
66 | // that RETURNS the new method. funcSource receives a single argument that is
67 | // the overridden method, it can be called from the new method. The overridden
68 | // method can be called like a regular function, it has the target permanently
69 | // bound to it so "this" will work correctly.
70 | function overrideMethod(target, methodName, funcSource) {
71 | var superFunc = target[methodName] || function() {};
72 | var superFuncBound = function() {
73 | return superFunc.apply(target, arguments);
74 | };
75 | target[methodName] = funcSource(superFuncBound);
76 | }
77 |
78 | // Add a method to delegator that, when invoked, calls
79 | // delegatee.methodName. If there is no such method on
80 | // the delegatee, but there was one on delegator before
81 | // delegateMethod was called, then the original version
82 | // is invoked instead.
83 | // For example:
84 | //
85 | // var a = {
86 | // method1: function() { console.log('a1'); }
87 | // method2: function() { console.log('a2'); }
88 | // };
89 | // var b = {
90 | // method1: function() { console.log('b1'); }
91 | // };
92 | // delegateMethod(a, b, "method1");
93 | // delegateMethod(a, b, "method2");
94 | // a.method1();
95 | // a.method2();
96 | //
97 | // The output would be "b1", "a2".
98 | function delegateMethod(delegator, delegatee, methodName) {
99 | var inherited = delegator[methodName];
100 | delegator[methodName] = function() {
101 | var target = delegatee;
102 | var method = delegatee[methodName];
103 |
104 | // The method doesn't exist on the delegatee. Instead,
105 | // call the method on the delegator, if it exists.
106 | if (!method) {
107 | target = delegator;
108 | method = inherited;
109 | }
110 |
111 | if (method) {
112 | return method.apply(target, arguments);
113 | }
114 | };
115 | }
116 |
117 | // Implement a vague facsimilie of jQuery's data method
118 | function elementData(el, name, value) {
119 | if (arguments.length == 2) {
120 | return el["htmlwidget_data_" + name];
121 | } else if (arguments.length == 3) {
122 | el["htmlwidget_data_" + name] = value;
123 | return el;
124 | } else {
125 | throw new Error("Wrong number of arguments for elementData: " +
126 | arguments.length);
127 | }
128 | }
129 |
130 | // http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
131 | function escapeRegExp(str) {
132 | return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
133 | }
134 |
135 | function hasClass(el, className) {
136 | var re = new RegExp("\\b" + escapeRegExp(className) + "\\b");
137 | return re.test(el.className);
138 | }
139 |
140 | // elements - array (or array-like object) of HTML elements
141 | // className - class name to test for
142 | // include - if true, only return elements with given className;
143 | // if false, only return elements *without* given className
144 | function filterByClass(elements, className, include) {
145 | var results = [];
146 | for (var i = 0; i < elements.length; i++) {
147 | if (hasClass(elements[i], className) == include)
148 | results.push(elements[i]);
149 | }
150 | return results;
151 | }
152 |
153 | function on(obj, eventName, func) {
154 | if (obj.addEventListener) {
155 | obj.addEventListener(eventName, func, false);
156 | } else if (obj.attachEvent) {
157 | obj.attachEvent(eventName, func);
158 | }
159 | }
160 |
161 | function off(obj, eventName, func) {
162 | if (obj.removeEventListener)
163 | obj.removeEventListener(eventName, func, false);
164 | else if (obj.detachEvent) {
165 | obj.detachEvent(eventName, func);
166 | }
167 | }
168 |
169 | // Translate array of values to top/right/bottom/left, as usual with
170 | // the "padding" CSS property
171 | // https://developer.mozilla.org/en-US/docs/Web/CSS/padding
172 | function unpackPadding(value) {
173 | if (typeof(value) === "number")
174 | value = [value];
175 | if (value.length === 1) {
176 | return {top: value[0], right: value[0], bottom: value[0], left: value[0]};
177 | }
178 | if (value.length === 2) {
179 | return {top: value[0], right: value[1], bottom: value[0], left: value[1]};
180 | }
181 | if (value.length === 3) {
182 | return {top: value[0], right: value[1], bottom: value[2], left: value[1]};
183 | }
184 | if (value.length === 4) {
185 | return {top: value[0], right: value[1], bottom: value[2], left: value[3]};
186 | }
187 | }
188 |
189 | // Convert an unpacked padding object to a CSS value
190 | function paddingToCss(paddingObj) {
191 | return paddingObj.top + "px " + paddingObj.right + "px " + paddingObj.bottom + "px " + paddingObj.left + "px";
192 | }
193 |
194 | // Makes a number suitable for CSS
195 | function px(x) {
196 | if (typeof(x) === "number")
197 | return x + "px";
198 | else
199 | return x;
200 | }
201 |
202 | // Retrieves runtime widget sizing information for an element.
203 | // The return value is either null, or an object with fill, padding,
204 | // defaultWidth, defaultHeight fields.
205 | function sizingPolicy(el) {
206 | var sizingEl = document.querySelector("script[data-for='" + el.id + "'][type='application/htmlwidget-sizing']");
207 | if (!sizingEl)
208 | return null;
209 | var sp = JSON.parse(sizingEl.textContent || sizingEl.text || "{}");
210 | if (viewerMode) {
211 | return sp.viewer;
212 | } else {
213 | return sp.browser;
214 | }
215 | }
216 |
217 | // @param tasks Array of strings (or falsy value, in which case no-op).
218 | // Each element must be a valid JavaScript expression that yields a
219 | // function. Or, can be an array of objects with "code" and "data"
220 | // properties; in this case, the "code" property should be a string
221 | // of JS that's an expr that yields a function, and "data" should be
222 | // an object that will be added as an additional argument when that
223 | // function is called.
224 | // @param target The object that will be "this" for each function
225 | // execution.
226 | // @param args Array of arguments to be passed to the functions. (The
227 | // same arguments will be passed to all functions.)
228 | function evalAndRun(tasks, target, args) {
229 | if (tasks) {
230 | forEach(tasks, function(task) {
231 | var theseArgs = args;
232 | if (typeof(task) === "object") {
233 | theseArgs = theseArgs.concat([task.data]);
234 | task = task.code;
235 | }
236 | var taskFunc = tryEval(task);
237 | if (typeof(taskFunc) !== "function") {
238 | throw new Error("Task must be a function! Source:\n" + task);
239 | }
240 | taskFunc.apply(target, theseArgs);
241 | });
242 | }
243 | }
244 |
245 | // Attempt eval() both with and without enclosing in parentheses.
246 | // Note that enclosing coerces a function declaration into
247 | // an expression that eval() can parse
248 | // (otherwise, a SyntaxError is thrown)
249 | function tryEval(code) {
250 | var result = null;
251 | try {
252 | result = eval("(" + code + ")");
253 | } catch(error) {
254 | if (!(error instanceof SyntaxError)) {
255 | throw error;
256 | }
257 | try {
258 | result = eval(code);
259 | } catch(e) {
260 | if (e instanceof SyntaxError) {
261 | throw error;
262 | } else {
263 | throw e;
264 | }
265 | }
266 | }
267 | return result;
268 | }
269 |
270 | function initSizing(el) {
271 | var sizing = sizingPolicy(el);
272 | if (!sizing)
273 | return;
274 |
275 | var cel = document.getElementById("htmlwidget_container");
276 | if (!cel)
277 | return;
278 |
279 | if (typeof(sizing.padding) !== "undefined") {
280 | document.body.style.margin = "0";
281 | document.body.style.padding = paddingToCss(unpackPadding(sizing.padding));
282 | }
283 |
284 | if (sizing.fill) {
285 | document.body.style.overflow = "hidden";
286 | document.body.style.width = "100%";
287 | document.body.style.height = "100%";
288 | document.documentElement.style.width = "100%";
289 | document.documentElement.style.height = "100%";
290 | cel.style.position = "absolute";
291 | var pad = unpackPadding(sizing.padding);
292 | cel.style.top = pad.top + "px";
293 | cel.style.right = pad.right + "px";
294 | cel.style.bottom = pad.bottom + "px";
295 | cel.style.left = pad.left + "px";
296 | el.style.width = "100%";
297 | el.style.height = "100%";
298 |
299 | return {
300 | getWidth: function() { return cel.getBoundingClientRect().width; },
301 | getHeight: function() { return cel.getBoundingClientRect().height; }
302 | };
303 |
304 | } else {
305 | el.style.width = px(sizing.width);
306 | el.style.height = px(sizing.height);
307 |
308 | return {
309 | getWidth: function() { return cel.getBoundingClientRect().width; },
310 | getHeight: function() { return cel.getBoundingClientRect().height; }
311 | };
312 | }
313 | }
314 |
315 | // Default implementations for methods
316 | var defaults = {
317 | find: function(scope) {
318 | return querySelectorAll(scope, "." + this.name);
319 | },
320 | renderError: function(el, err) {
321 | var $el = $(el);
322 |
323 | this.clearError(el);
324 |
325 | // Add all these error classes, as Shiny does
326 | var errClass = "shiny-output-error";
327 | if (err.type !== null) {
328 | // use the classes of the error condition as CSS class names
329 | errClass = errClass + " " + $.map(asArray(err.type), function(type) {
330 | return errClass + "-" + type;
331 | }).join(" ");
332 | }
333 | errClass = errClass + " htmlwidgets-error";
334 |
335 | // Is el inline or block? If inline or inline-block, just display:none it
336 | // and add an inline error.
337 | var display = $el.css("display");
338 | $el.data("restore-display-mode", display);
339 |
340 | if (display === "inline" || display === "inline-block") {
341 | $el.hide();
342 | if (err.message !== "") {
343 | var errorSpan = $("").addClass(errClass);
344 | errorSpan.text(err.message);
345 | $el.after(errorSpan);
346 | }
347 | } else if (display === "block") {
348 | // If block, add an error just after the el, set visibility:none on the
349 | // el, and position the error to be on top of the el.
350 | // Mark it with a unique ID and CSS class so we can remove it later.
351 | $el.css("visibility", "hidden");
352 | if (err.message !== "") {
353 | var errorDiv = $("
").addClass(errClass).css("position", "absolute")
354 | .css("top", el.offsetTop)
355 | .css("left", el.offsetLeft)
356 | // setting width can push out the page size, forcing otherwise
357 | // unnecessary scrollbars to appear and making it impossible for
358 | // the element to shrink; so use max-width instead
359 | .css("maxWidth", el.offsetWidth)
360 | .css("height", el.offsetHeight);
361 | errorDiv.text(err.message);
362 | $el.after(errorDiv);
363 |
364 | // Really dumb way to keep the size/position of the error in sync with
365 | // the parent element as the window is resized or whatever.
366 | var intId = setInterval(function() {
367 | if (!errorDiv[0].parentElement) {
368 | clearInterval(intId);
369 | return;
370 | }
371 | errorDiv
372 | .css("top", el.offsetTop)
373 | .css("left", el.offsetLeft)
374 | .css("maxWidth", el.offsetWidth)
375 | .css("height", el.offsetHeight);
376 | }, 500);
377 | }
378 | }
379 | },
380 | clearError: function(el) {
381 | var $el = $(el);
382 | var display = $el.data("restore-display-mode");
383 | $el.data("restore-display-mode", null);
384 |
385 | if (display === "inline" || display === "inline-block") {
386 | if (display)
387 | $el.css("display", display);
388 | $(el.nextSibling).filter(".htmlwidgets-error").remove();
389 | } else if (display === "block"){
390 | $el.css("visibility", "inherit");
391 | $(el.nextSibling).filter(".htmlwidgets-error").remove();
392 | }
393 | },
394 | sizing: {}
395 | };
396 |
397 | // Called by widget bindings to register a new type of widget. The definition
398 | // object can contain the following properties:
399 | // - name (required) - A string indicating the binding name, which will be
400 | // used by default as the CSS classname to look for.
401 | // - initialize (optional) - A function(el) that will be called once per
402 | // widget element; if a value is returned, it will be passed as the third
403 | // value to renderValue.
404 | // - renderValue (required) - A function(el, data, initValue) that will be
405 | // called with data. Static contexts will cause this to be called once per
406 | // element; Shiny apps will cause this to be called multiple times per
407 | // element, as the data changes.
408 | window.HTMLWidgets.widget = function(definition) {
409 | if (!definition.name) {
410 | throw new Error("Widget must have a name");
411 | }
412 | if (!definition.type) {
413 | throw new Error("Widget must have a type");
414 | }
415 | // Currently we only support output widgets
416 | if (definition.type !== "output") {
417 | throw new Error("Unrecognized widget type '" + definition.type + "'");
418 | }
419 | // TODO: Verify that .name is a valid CSS classname
420 |
421 | // Support new-style instance-bound definitions. Old-style class-bound
422 | // definitions have one widget "object" per widget per type/class of
423 | // widget; the renderValue and resize methods on such widget objects
424 | // take el and instance arguments, because the widget object can't
425 | // store them. New-style instance-bound definitions have one widget
426 | // object per widget instance; the definition that's passed in doesn't
427 | // provide renderValue or resize methods at all, just the single method
428 | // factory(el, width, height)
429 | // which returns an object that has renderValue(x) and resize(w, h).
430 | // This enables a far more natural programming style for the widget
431 | // author, who can store per-instance state using either OO-style
432 | // instance fields or functional-style closure variables (I guess this
433 | // is in contrast to what can only be called C-style pseudo-OO which is
434 | // what we required before).
435 | if (definition.factory) {
436 | definition = createLegacyDefinitionAdapter(definition);
437 | }
438 |
439 | if (!definition.renderValue) {
440 | throw new Error("Widget must have a renderValue function");
441 | }
442 |
443 | // For static rendering (non-Shiny), use a simple widget registration
444 | // scheme. We also use this scheme for Shiny apps/documents that also
445 | // contain static widgets.
446 | window.HTMLWidgets.widgets = window.HTMLWidgets.widgets || [];
447 | // Merge defaults into the definition; don't mutate the original definition.
448 | var staticBinding = extend({}, defaults, definition);
449 | overrideMethod(staticBinding, "find", function(superfunc) {
450 | return function(scope) {
451 | var results = superfunc(scope);
452 | // Filter out Shiny outputs, we only want the static kind
453 | return filterByClass(results, "html-widget-output", false);
454 | };
455 | });
456 | window.HTMLWidgets.widgets.push(staticBinding);
457 |
458 | if (shinyMode) {
459 | // Shiny is running. Register the definition with an output binding.
460 | // The definition itself will not be the output binding, instead
461 | // we will make an output binding object that delegates to the
462 | // definition. This is because we foolishly used the same method
463 | // name (renderValue) for htmlwidgets definition and Shiny bindings
464 | // but they actually have quite different semantics (the Shiny
465 | // bindings receive data that includes lots of metadata that it
466 | // strips off before calling htmlwidgets renderValue). We can't
467 | // just ignore the difference because in some widgets it's helpful
468 | // to call this.renderValue() from inside of resize(), and if
469 | // we're not delegating, then that call will go to the Shiny
470 | // version instead of the htmlwidgets version.
471 |
472 | // Merge defaults with definition, without mutating either.
473 | var bindingDef = extend({}, defaults, definition);
474 |
475 | // This object will be our actual Shiny binding.
476 | var shinyBinding = new Shiny.OutputBinding();
477 |
478 | // With a few exceptions, we'll want to simply use the bindingDef's
479 | // version of methods if they are available, otherwise fall back to
480 | // Shiny's defaults. NOTE: If Shiny's output bindings gain additional
481 | // methods in the future, and we want them to be overrideable by
482 | // HTMLWidget binding definitions, then we'll need to add them to this
483 | // list.
484 | delegateMethod(shinyBinding, bindingDef, "getId");
485 | delegateMethod(shinyBinding, bindingDef, "onValueChange");
486 | delegateMethod(shinyBinding, bindingDef, "onValueError");
487 | delegateMethod(shinyBinding, bindingDef, "renderError");
488 | delegateMethod(shinyBinding, bindingDef, "clearError");
489 | delegateMethod(shinyBinding, bindingDef, "showProgress");
490 |
491 | // The find, renderValue, and resize are handled differently, because we
492 | // want to actually decorate the behavior of the bindingDef methods.
493 |
494 | shinyBinding.find = function(scope) {
495 | var results = bindingDef.find(scope);
496 |
497 | // Only return elements that are Shiny outputs, not static ones
498 | var dynamicResults = results.filter(".html-widget-output");
499 |
500 | // It's possible that whatever caused Shiny to think there might be
501 | // new dynamic outputs, also caused there to be new static outputs.
502 | // Since there might be lots of different htmlwidgets bindings, we
503 | // schedule execution for later--no need to staticRender multiple
504 | // times.
505 | if (results.length !== dynamicResults.length)
506 | scheduleStaticRender();
507 |
508 | return dynamicResults;
509 | };
510 |
511 | // Wrap renderValue to handle initialization, which unfortunately isn't
512 | // supported natively by Shiny at the time of this writing.
513 |
514 | shinyBinding.renderValue = function(el, data) {
515 | Shiny.renderDependencies(data.deps);
516 | // Resolve strings marked as javascript literals to objects
517 | if (!(data.evals instanceof Array)) data.evals = [data.evals];
518 | for (var i = 0; data.evals && i < data.evals.length; i++) {
519 | window.HTMLWidgets.evaluateStringMember(data.x, data.evals[i]);
520 | }
521 | if (!bindingDef.renderOnNullValue) {
522 | if (data.x === null) {
523 | el.style.visibility = "hidden";
524 | return;
525 | } else {
526 | el.style.visibility = "inherit";
527 | }
528 | }
529 | if (!elementData(el, "initialized")) {
530 | initSizing(el);
531 |
532 | elementData(el, "initialized", true);
533 | if (bindingDef.initialize) {
534 | var rect = el.getBoundingClientRect();
535 | var result = bindingDef.initialize(el, rect.width, rect.height);
536 | elementData(el, "init_result", result);
537 | }
538 | }
539 | bindingDef.renderValue(el, data.x, elementData(el, "init_result"));
540 | evalAndRun(data.jsHooks.render, elementData(el, "init_result"), [el, data.x]);
541 | };
542 |
543 | // Only override resize if bindingDef implements it
544 | if (bindingDef.resize) {
545 | shinyBinding.resize = function(el, width, height) {
546 | // Shiny can call resize before initialize/renderValue have been
547 | // called, which doesn't make sense for widgets.
548 | if (elementData(el, "initialized")) {
549 | bindingDef.resize(el, width, height, elementData(el, "init_result"));
550 | }
551 | };
552 | }
553 |
554 | Shiny.outputBindings.register(shinyBinding, bindingDef.name);
555 | }
556 | };
557 |
558 | var scheduleStaticRenderTimerId = null;
559 | function scheduleStaticRender() {
560 | if (!scheduleStaticRenderTimerId) {
561 | scheduleStaticRenderTimerId = setTimeout(function() {
562 | scheduleStaticRenderTimerId = null;
563 | window.HTMLWidgets.staticRender();
564 | }, 1);
565 | }
566 | }
567 |
568 | // Render static widgets after the document finishes loading
569 | // Statically render all elements that are of this widget's class
570 | window.HTMLWidgets.staticRender = function() {
571 | var bindings = window.HTMLWidgets.widgets || [];
572 | forEach(bindings, function(binding) {
573 | var matches = binding.find(document.documentElement);
574 | forEach(matches, function(el) {
575 | var sizeObj = initSizing(el, binding);
576 |
577 | var getSize = function(el) {
578 | if (sizeObj) {
579 | return {w: sizeObj.getWidth(), h: sizeObj.getHeight()}
580 | } else {
581 | var rect = el.getBoundingClientRect();
582 | return {w: rect.width, h: rect.height}
583 | }
584 | };
585 |
586 | if (hasClass(el, "html-widget-static-bound"))
587 | return;
588 | el.className = el.className + " html-widget-static-bound";
589 |
590 | var initResult;
591 | if (binding.initialize) {
592 | var size = getSize(el);
593 | initResult = binding.initialize(el, size.w, size.h);
594 | elementData(el, "init_result", initResult);
595 | }
596 |
597 | if (binding.resize) {
598 | var lastSize = getSize(el);
599 | var resizeHandler = function(e) {
600 | var size = getSize(el);
601 | if (size.w === 0 && size.h === 0)
602 | return;
603 | if (size.w === lastSize.w && size.h === lastSize.h)
604 | return;
605 | lastSize = size;
606 | binding.resize(el, size.w, size.h, initResult);
607 | };
608 |
609 | on(window, "resize", resizeHandler);
610 |
611 | // This is needed for cases where we're running in a Shiny
612 | // app, but the widget itself is not a Shiny output, but
613 | // rather a simple static widget. One example of this is
614 | // an rmarkdown document that has runtime:shiny and widget
615 | // that isn't in a render function. Shiny only knows to
616 | // call resize handlers for Shiny outputs, not for static
617 | // widgets, so we do it ourselves.
618 | if (window.jQuery) {
619 | window.jQuery(document).on(
620 | "shown.htmlwidgets shown.bs.tab.htmlwidgets shown.bs.collapse.htmlwidgets",
621 | resizeHandler
622 | );
623 | window.jQuery(document).on(
624 | "hidden.htmlwidgets hidden.bs.tab.htmlwidgets hidden.bs.collapse.htmlwidgets",
625 | resizeHandler
626 | );
627 | }
628 |
629 | // This is needed for the specific case of ioslides, which
630 | // flips slides between display:none and display:block.
631 | // Ideally we would not have to have ioslide-specific code
632 | // here, but rather have ioslides raise a generic event,
633 | // but the rmarkdown package just went to CRAN so the
634 | // window to getting that fixed may be long.
635 | if (window.addEventListener) {
636 | // It's OK to limit this to window.addEventListener
637 | // browsers because ioslides itself only supports
638 | // such browsers.
639 | on(document, "slideenter", resizeHandler);
640 | on(document, "slideleave", resizeHandler);
641 | }
642 | }
643 |
644 | var scriptData = document.querySelector("script[data-for='" + el.id + "'][type='application/json']");
645 | if (scriptData) {
646 | var data = JSON.parse(scriptData.textContent || scriptData.text);
647 | // Resolve strings marked as javascript literals to objects
648 | if (!(data.evals instanceof Array)) data.evals = [data.evals];
649 | for (var k = 0; data.evals && k < data.evals.length; k++) {
650 | window.HTMLWidgets.evaluateStringMember(data.x, data.evals[k]);
651 | }
652 | binding.renderValue(el, data.x, initResult);
653 | evalAndRun(data.jsHooks.render, initResult, [el, data.x]);
654 | }
655 | });
656 | });
657 |
658 | invokePostRenderHandlers();
659 | }
660 |
661 |
662 | function has_jQuery3() {
663 | if (!window.jQuery) {
664 | return false;
665 | }
666 | var $version = window.jQuery.fn.jquery;
667 | var $major_version = parseInt($version.split(".")[0]);
668 | return $major_version >= 3;
669 | }
670 |
671 | /*
672 | / Shiny 1.4 bumped jQuery from 1.x to 3.x which means jQuery's
673 | / on-ready handler (i.e., $(fn)) is now asyncronous (i.e., it now
674 | / really means $(setTimeout(fn)).
675 | / https://jquery.com/upgrade-guide/3.0/#breaking-change-document-ready-handlers-are-now-asynchronous
676 | /
677 | / Since Shiny uses $() to schedule initShiny, shiny>=1.4 calls initShiny
678 | / one tick later than it did before, which means staticRender() is
679 | / called renderValue() earlier than (advanced) widget authors might be expecting.
680 | / https://github.com/rstudio/shiny/issues/2630
681 | /
682 | / For a concrete example, leaflet has some methods (e.g., updateBounds)
683 | / which reference Shiny methods registered in initShiny (e.g., setInputValue).
684 | / Since leaflet is privy to this life-cycle, it knows to use setTimeout() to
685 | / delay execution of those methods (until Shiny methods are ready)
686 | / https://github.com/rstudio/leaflet/blob/18ec981/javascript/src/index.js#L266-L268
687 | /
688 | / Ideally widget authors wouldn't need to use this setTimeout() hack that
689 | / leaflet uses to call Shiny methods on a staticRender(). In the long run,
690 | / the logic initShiny should be broken up so that method registration happens
691 | / right away, but binding happens later.
692 | */
693 | function maybeStaticRenderLater() {
694 | if (shinyMode && has_jQuery3()) {
695 | window.jQuery(window.HTMLWidgets.staticRender);
696 | } else {
697 | window.HTMLWidgets.staticRender();
698 | }
699 | }
700 |
701 | if (document.addEventListener) {
702 | document.addEventListener("DOMContentLoaded", function() {
703 | document.removeEventListener("DOMContentLoaded", arguments.callee, false);
704 | maybeStaticRenderLater();
705 | }, false);
706 | } else if (document.attachEvent) {
707 | document.attachEvent("onreadystatechange", function() {
708 | if (document.readyState === "complete") {
709 | document.detachEvent("onreadystatechange", arguments.callee);
710 | maybeStaticRenderLater();
711 | }
712 | });
713 | }
714 |
715 |
716 | window.HTMLWidgets.getAttachmentUrl = function(depname, key) {
717 | // If no key, default to the first item
718 | if (typeof(key) === "undefined")
719 | key = 1;
720 |
721 | var link = document.getElementById(depname + "-" + key + "-attachment");
722 | if (!link) {
723 | throw new Error("Attachment " + depname + "/" + key + " not found in document");
724 | }
725 | return link.getAttribute("href");
726 | };
727 |
728 | window.HTMLWidgets.dataframeToD3 = function(df) {
729 | var names = [];
730 | var length;
731 | for (var name in df) {
732 | if (df.hasOwnProperty(name))
733 | names.push(name);
734 | if (typeof(df[name]) !== "object" || typeof(df[name].length) === "undefined") {
735 | throw new Error("All fields must be arrays");
736 | } else if (typeof(length) !== "undefined" && length !== df[name].length) {
737 | throw new Error("All fields must be arrays of the same length");
738 | }
739 | length = df[name].length;
740 | }
741 | var results = [];
742 | var item;
743 | for (var row = 0; row < length; row++) {
744 | item = {};
745 | for (var col = 0; col < names.length; col++) {
746 | item[names[col]] = df[names[col]][row];
747 | }
748 | results.push(item);
749 | }
750 | return results;
751 | };
752 |
753 | window.HTMLWidgets.transposeArray2D = function(array) {
754 | if (array.length === 0) return array;
755 | var newArray = array[0].map(function(col, i) {
756 | return array.map(function(row) {
757 | return row[i]
758 | })
759 | });
760 | return newArray;
761 | };
762 | // Split value at splitChar, but allow splitChar to be escaped
763 | // using escapeChar. Any other characters escaped by escapeChar
764 | // will be included as usual (including escapeChar itself).
765 | function splitWithEscape(value, splitChar, escapeChar) {
766 | var results = [];
767 | var escapeMode = false;
768 | var currentResult = "";
769 | for (var pos = 0; pos < value.length; pos++) {
770 | if (!escapeMode) {
771 | if (value[pos] === splitChar) {
772 | results.push(currentResult);
773 | currentResult = "";
774 | } else if (value[pos] === escapeChar) {
775 | escapeMode = true;
776 | } else {
777 | currentResult += value[pos];
778 | }
779 | } else {
780 | currentResult += value[pos];
781 | escapeMode = false;
782 | }
783 | }
784 | if (currentResult !== "") {
785 | results.push(currentResult);
786 | }
787 | return results;
788 | }
789 | // Function authored by Yihui/JJ Allaire
790 | window.HTMLWidgets.evaluateStringMember = function(o, member) {
791 | var parts = splitWithEscape(member, '.', '\\');
792 | for (var i = 0, l = parts.length; i < l; i++) {
793 | var part = parts[i];
794 | // part may be a character or 'numeric' member name
795 | if (o !== null && typeof o === "object" && part in o) {
796 | if (i == (l - 1)) { // if we are at the end of the line then evalulate
797 | if (typeof o[part] === "string")
798 | o[part] = tryEval(o[part]);
799 | } else { // otherwise continue to next embedded object
800 | o = o[part];
801 | }
802 | }
803 | }
804 | };
805 |
806 | // Retrieve the HTMLWidget instance (i.e. the return value of an
807 | // HTMLWidget binding's initialize() or factory() function)
808 | // associated with an element, or null if none.
809 | window.HTMLWidgets.getInstance = function(el) {
810 | return elementData(el, "init_result");
811 | };
812 |
813 | // Finds the first element in the scope that matches the selector,
814 | // and returns the HTMLWidget instance (i.e. the return value of
815 | // an HTMLWidget binding's initialize() or factory() function)
816 | // associated with that element, if any. If no element matches the
817 | // selector, or the first matching element has no HTMLWidget
818 | // instance associated with it, then null is returned.
819 | //
820 | // The scope argument is optional, and defaults to window.document.
821 | window.HTMLWidgets.find = function(scope, selector) {
822 | if (arguments.length == 1) {
823 | selector = scope;
824 | scope = document;
825 | }
826 |
827 | var el = scope.querySelector(selector);
828 | if (el === null) {
829 | return null;
830 | } else {
831 | return window.HTMLWidgets.getInstance(el);
832 | }
833 | };
834 |
835 | // Finds all elements in the scope that match the selector, and
836 | // returns the HTMLWidget instances (i.e. the return values of
837 | // an HTMLWidget binding's initialize() or factory() function)
838 | // associated with the elements, in an array. If elements that
839 | // match the selector don't have an associated HTMLWidget
840 | // instance, the returned array will contain nulls.
841 | //
842 | // The scope argument is optional, and defaults to window.document.
843 | window.HTMLWidgets.findAll = function(scope, selector) {
844 | if (arguments.length == 1) {
845 | selector = scope;
846 | scope = document;
847 | }
848 |
849 | var nodes = scope.querySelectorAll(selector);
850 | var results = [];
851 | for (var i = 0; i < nodes.length; i++) {
852 | results.push(window.HTMLWidgets.getInstance(nodes[i]));
853 | }
854 | return results;
855 | };
856 |
857 | var postRenderHandlers = [];
858 | function invokePostRenderHandlers() {
859 | while (postRenderHandlers.length) {
860 | var handler = postRenderHandlers.shift();
861 | if (handler) {
862 | handler();
863 | }
864 | }
865 | }
866 |
867 | // Register the given callback function to be invoked after the
868 | // next time static widgets are rendered.
869 | window.HTMLWidgets.addPostRenderHandler = function(callback) {
870 | postRenderHandlers.push(callback);
871 | };
872 |
873 | // Takes a new-style instance-bound definition, and returns an
874 | // old-style class-bound definition. This saves us from having
875 | // to rewrite all the logic in this file to accomodate both
876 | // types of definitions.
877 | function createLegacyDefinitionAdapter(defn) {
878 | var result = {
879 | name: defn.name,
880 | type: defn.type,
881 | initialize: function(el, width, height) {
882 | return defn.factory(el, width, height);
883 | },
884 | renderValue: function(el, x, instance) {
885 | return instance.renderValue(x);
886 | },
887 | resize: function(el, width, height, instance) {
888 | return instance.resize(width, height);
889 | }
890 | };
891 |
892 | if (defn.find)
893 | result.find = defn.find;
894 | if (defn.renderError)
895 | result.renderError = defn.renderError;
896 | if (defn.clearError)
897 | result.clearError = defn.clearError;
898 |
899 | return result;
900 | }
901 | })();
902 |
--------------------------------------------------------------------------------