-
Notifications
You must be signed in to change notification settings - Fork 39
/
programming.R
120 lines (87 loc) · 2.46 KB
/
programming.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# libraries ----
library(tidyverse)
# data ----
url <- 'https://raw.githubusercontent.com/OHI-Science/data-science-training/master/data/gapminder.csv'
gapminder <- read_csv(url) # View(gapminder)
# ggplot: after filter by country ----
gapminder %>%
filter(country == "Afghanistan") %>%
ggplot(aes(x = year, y = gdpPercap)) +
geom_point() +
geom_smooth() +
labs(title = "Afghanistan")
# ggsave: after filter by country & plot ----
png <- "gdp_Afghanistan.png"
g <- gapminder %>%
filter(country == "Afghanistan") %>%
ggplot(aes(x = year, y = gdpPercap)) +
geom_point() +
geom_smooth() +
labs(title = "Afghanistan")
ggsave(filename = png, plot = g)
# function: for plotting any country ----
plot_country <- function(cntry){
png <- paste0("gdp_", cntry, ".png")
g <- gapminder %>%
filter(country == cntry) %>%
ggplot(aes(x = year, y = gdpPercap)) +
geom_point() +
geom_smooth() +
labs(title = cntry)
ggsave(filename = png, plot = g)
}
plot_country("Afghanistan")
# for: loop to iterate over some countries ----
countries <- c("United States", "Mexico")
for (k in countries){
plot_country(k)
}
# debug: inside function and for loop ----
plot_country <- function(cntry){
png <- paste0("gdp_", cntry, ".png")
#browser()
cat("plot_country(", cntry,") -> ", png, "\n")
g <- gapminder %>%
filter(country == cntry) %>%
ggplot(aes(x = year, y = gdpPercap)) +
geom_point() +
geom_smooth() +
labs(title = cntry)
ggsave(filename = png, plot = g)
}
countries <- c("Fiji", "Peru", "Mexico")
for (k in countries){
#browser()
cat("for () { k: ", k," }\n")
plot_country(k)
}
# if: output to different folder based on gdp ----
dir.create("developed")
dir.create("developing")
plot_country <- function(cntry, png){
cat("plot_country(", cntry,", ", png, ")\n")
g <- gapminder %>%
filter(country == cntry) %>%
ggplot(aes(x = year, y = gdpPercap)) +
geom_point() +
geom_smooth() +
labs(title = cntry)
ggsave(filename = png, plot = g)
}
is_developed <- function(cntry, threshold = 12000){
#browser() # cntry <- "Canada"
gapminder %>%
filter(country == cntry) %>%
summarise(
mean_gdp = mean(gdpPercap)) %>%
.$mean_gdp >= threshold
}
countries <- c("United States", "Canada", "Afghanistan", "Rwanda")
for (k in countries){
if (is_developed(k)){
png <- paste0("developed/gdp_", k, ".png")
} else {
png <- paste0("developing/gdp_", k, ".png")
}
plot_country(k, png)
}