Hello! This RMD contains some code of how to create a function. I am proud of this because it can be used to carry our reptitive bits of code, and was really useful for when trying to calculate certain values in R.
#Load packages
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6 ✔ purrr 0.3.4
## ✔ tibble 3.1.7 ✔ dplyr 1.0.9
## ✔ tidyr 1.2.0 ✔ stringr 1.4.0
## ✔ readr 2.1.2 ✔ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
#Read CSV File
aaec <- read_csv(file = "AgeAdvantagesEmotionCovid_Data.csv")
## Rows: 945 Columns: 107
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (10): ResponseId, gender_all, race_all, educ, income, emp, livealone, ge...
## dbl (97): f_aff, f_ener, f_acc, f_ang, f_int, f_calm, f_app, f_cont, f_dis, ...
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#Creating data frame of required variables
health_and_risk <- aaec %>%
select(risk_self, risk_comp, risk_pop, health)
#Create function that produces descriptive values
healthsummary.fun <- function(var1) {health_and_risk %>%
summarise(
mean = mean(var1),
sd = sd(var1),
median = median(var1),
min = min(var1),
max = max(var1)
)
}
#Run function for different variables
risk_self <- healthsummary.fun(var1 =aaec$risk_self)
risk_comp <- healthsummary.fun(var1 =aaec$risk_comp)
risk_pop <- healthsummary.fun(var1 =aaec$risk_pop)
health <- healthsummary.fun(var1 =aaec$health)
#Creating a table for the descriptives
table_health_and_risk <- rbind(risk_self, risk_comp, risk_pop, health)
rownames(table_health_and_risk) <- c("risk_self", "risk_comp", "risk_pop", "health")
## Warning: Setting row names on a tibble is deprecated.
print(table_health_and_risk)
## # A tibble: 4 × 5
## mean sd median min max
## * <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 2.36 1.11 2 0 5
## 2 2.45 1.34 2 0 5
## 3 2.97 0.939 3 0 5
## 4 3.36 0.986 3 1 5