# Define the function
square_number <- function(x) {
result <- x^2
return(result)
}
# Use the function
square_number(55)
[1] 3025
October 8, 2024
In the Tidyverse, ridy evaluation allows you to reference a column without using quotes or referencing the data frame
vs.
or
dplyr
and ggplot2
assume that any argument passed to them is already a column name.{{}}
in functions.data[[]]
!!sym()
in some contextsget()
, eval(parse())
,aes_string()
and !!enquo()
library(rnaturalearth)
library(dplyr)
library(ggplot2)
library(ggthemes)
library(wbstats)
create_map <- function(var_id, title, legend_title, theme, direction){
ne_countries(scale = "medium", returnclass = "sf") |>
left_join(
wb_data(var_id, mrnev = 1),
join_by(iso_a3 == iso3c)
) |>
filter(name != "Antarctica") |>
ggplot() +
geom_sf(aes(fill = .data[[var_id]])) +
labs(
title = title,
fill = legend_title,
caption = "Source: World Bank Development Indicators"
) +
theme_map() +
theme(
plot.title = element_text(face = "bold"),
) +
scale_fill_viridis_c(
option = theme,
direction = direction
)
}
Save the source code in a folder…
and call in your document…
source()
and then the function in your Quarto document10:00
10:00
# var_id = any World Bank indicator
# mrv = number of most recent values
# group_var = column to group by (country or date)
mean_wb_data <- function(var_id, mrv, group_var){
wb_data(var_id, mrv = mrv) |>
group_by( {{ group_var }}) |>
summarize(mean_value = mean(.data[[var_id]], na.rm = TRUE))
}
# Example call
mean_wb_data("SL.TLF.CACT.FE.ZS", 3, date)
create_line_chart <- function(data, x_var, y_var, color_var, title, x_label,
y_label, legend_title, color_palette = "turbo",
palette_end = 0.8) {
ggplot(data, aes(x = {{ x_var }}, y = {{ y_var }}, color = {{ color_var }})) +
geom_line() +
labs(
title = title,
x = x_label,
y = y_label
) +
scale_color_viridis_d(
name = legend_title,
option = color_palette,
end = palette_end
) +
theme_minimal()
}
# Example call
create_line_chart(
data = brics_dem,
x_var = year,
y_var = v2x_polyarchy,
color_var = country_name,
title = "Democracy in the BRICS Nations",
x_label = "Year",
y_label = "Polyarchy Score",
legend_title = "Index"
)