knitr::opts_chunk$set(
echo = TRUE,
message = FALSE,
warning = FALSE
)Práca s databázou
Spracované a inšpirované Notebookom Jason Locklin: Introduction to R for Education Data Analysis and Visualization
Práca s údajmi
Tradičná práca s databázou
Pre prácu s údajmi (databázou) používame najčastejšie dátový typ .data.frame.. Je to tabuľka, ktorá pozostáva zo stĺpcov rozličných typov. Jeden riadok pritom predstavuje jeden záznam databázy.
Príklad
Majme údaje o žiakoch, ktoré predstavujú tri premenné - Meno, Vek a Body:
# Working with data frames
Meno = c("Jana", "Jozef", "Mária")
Vek = c(10, 11, 9)
Body = c(85, 92, 78)Tieto tri premenné nie sú zatiaľ nijako prepojené, predstavujú izolované stĺpce tabuľky. Do tabuľky ich spojíme nasledovne
udaje <- data.frame(Meno,Vek,Body)
print(udaje) Meno Vek Body
1 Jana 10 85
2 Jozef 11 92
3 Mária 9 78
Vysvetlenie: DataFrame má tri stĺpce: Meno, Vek a Body. Niektoré operácie s údajmi organizovanými v .data.frame. sú uvedené nasledovne
print(udaje$Vek) # takto adresujeme jednotlivé premenné v data.frame[1] 10 11 9
print(mean(udaje$Vek)) # priemerny vek[1] 10
print(udaje[Meno=="Jozef",]) # adresovanie celého riadku Meno Vek Body
2 Jozef 11 92
print(udaje[3,]) # ina moznost adresovania celeho riadku Meno Vek Body
3 Mária 9 78
print(udaje[,2:3]) # vypisanie druheho a tretieho stlpca tabulky Vek Body
1 10 85
2 11 92
3 9 78
print(udaje[1,1]) # vypisanie jednej bunky tabulky[1] "Jana"
summary(udaje) # zakladna deskriptivna statistika celej tabulky Meno Vek Body
Length :3 Min. : 9.0 Min. :78.0
N.unique :3 1st Qu.: 9.5 1st Qu.:81.5
N.blank :0 Median :10.0 Median :85.0
Min.nchar:4 Mean :10.0 Mean :85.0
Max.nchar:5 3rd Qu.:10.5 3rd Qu.:88.5
Max. :11.0 Max. :92.0
Ak chceme pridať k tabuľke dodatočný stĺpec, potom to robíme nasledovne
MaAuto <- c(TRUE,FALSE,TRUE)
udaje <- cbind(udaje,MaAuto)
print(udaje) Meno Vek Body MaAuto
1 Jana 10 85 TRUE
2 Jozef 11 92 FALSE
3 Mária 9 78 TRUE
Ak chceme pridať riadok, potom
# New record (must match column order/types)
novy.riadok <- data.frame(Meno = "Diana", Vek = 22.485, Body = 42,MaAuto = FALSE)
# Append
udaje <- rbind(udaje, novy.riadok)
print(udaje) Meno Vek Body MaAuto
1 Jana 10.000 85 TRUE
2 Jozef 11.000 92 FALSE
3 Mária 9.000 78 TRUE
4 Diana 22.485 42 FALSE
Tabuľky v prostredí kableextra
library(knitr)
library(kableExtra)
kable(
udaje,
# format,
digits = 2,
# row.names = NA,
# col.names = NA,
align=c("l","c","l","r"),
caption = "Toto je tabuľka"
# label = NULL,
# format.args = list(),
# escape = TRUE,
# ...
) %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE,
position = "center")| Meno | Vek | Body | MaAuto |
|---|---|---|---|
| Jana | 10.00 | 85 | TRUE |
| Jozef | 11.00 | 92 | FALSE |
| Mária | 9.00 | 78 | TRUE |
| Diana | 22.48 | 42 | FALSE |
Tidyverse - moderná práca s údajmi
Tidyverse je súbor knižníc, ktoré majú zjednodušiť prácu s údajmi. Majú jednotný komunikačný štandard, vzájomne sa doplňujú.
# Load tidyverse
library(tidyverse)dplyr - pre manipuláciu s údajmi
.dplyr. poskytuje základné možnosti manipulácie s údajmi, ako napr.:
filter(): vyberá riadky
select(): vyberá stĺpce
mutate(): vytvára nové stĺpce tabuľky
arrange(): triedi riadky
summarise(): sumarizuje
V nasledovnej ukážke využijeme tzv. .pipes. %>% alebo %<% umožňuje posielať výsledky z jednej funkcie priamo do volanie nasledovnej funkcie. To umožňuje ľahšiu čitateľnosť kódov, konvencia sa ujala a má široké použitie.
Výber a triedenie
# výber a následné triedenie
udaje %>%
filter(Body > 50) %>% # vybera zaznamy s poctom bodov viac, ako 50
arrange(desc(Body)) %>% # vysledny subor triedi zostupne podla premennej Body
kable %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE,
position = "center"
)| Meno | Vek | Body | MaAuto |
|---|---|---|---|
| Jozef | 11 | 92 | FALSE |
| Jana | 10 | 85 | TRUE |
| Mária | 9 | 78 | TRUE |
Zoskupenie a sumarizácia
# Zoskupí and sumarizuje
udaje %>%
group_by(MaAuto) %>% # zoskupi zaznamy podla premennej MaAuto a vypocita za kazdu skupinu jej priemer Body
summarise( # a taktiez spocita pocetnosti oboch skupin
Priem.Body = mean(Body),
count = n()
) %>%
kable(
caption = "Priemerné Body podľa premennej MaAuto",
col.names = c("Má Auto", "Priemer Body", "Počet"),
align = "c"
) %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE,
position = "center"
)| Má Auto | Priemer Body | Počet |
|---|---|---|
| FALSE | 67.0 | 2 |
| TRUE | 81.5 | 2 |
Vytváranie novej premennej
# Vytváranie novej premennej
udaje %>%
mutate(
grade = case_when( # vytvara novu premennu grade podla nasledovnej relacnej schemy
Body >= 90 ~ "A",
Body >= 80 ~ "B",
Body >= 70 ~ "C",
TRUE ~ "D"
),
VekPoPlnoletosti = round(Vek-18,0)
) %>%
kable %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE,
position = "center"
) | Meno | Vek | Body | MaAuto | grade | VekPoPlnoletosti |
|---|---|---|---|---|---|
| Jana | 10.000 | 85 | TRUE | B | -8 |
| Jozef | 11.000 | 92 | FALSE | A | -7 |
| Mária | 9.000 | 78 | TRUE | C | -9 |
| Diana | 22.485 | 42 | FALSE | D | 4 |
Import údajov z otv. databáz
- Mendeley Data Tuto sa dostaneme z Mendeley Data, kde si údaje viete voľne stiahnúť. Údaje sa vzťahujú k už publikovaným článkom vo vydavateľstve Elsevier. Výber sa dá urobiť jednoducho zadaním kľúčových slov.
- Kaggle Data Tuto sa dostaneme z Kaggle Datasets, kde si údaje viete voľne stiahnúť. Údaje sa vzťahujú k projektom podporovaným Kaggle. Výber sa dá urobiť jednoducho zadaním kľúčových slov.
- Databázy knižníc R - .library(datasets). alebo .library(wooldridge). ale aj iné - stačí si dať príkaz data()
library(datasets)
# datasets available in the 'datasets' package - nasledovne kody za mna urobil Chat GPT
ds <- as.data.frame(utils::data(package = "datasets")$results)[, c("Item","Title")]
knitr::kable(head(ds, 20), col.names = c("Dataset", "Title")) # prvych 20 databaz| Dataset | Title |
|---|---|
| AirPassengers | Monthly Airline Passenger Numbers 1949-1960 |
| BJsales | Sales Data with Leading Indicator |
| BJsales.lead (BJsales) | Sales Data with Leading Indicator |
| BOD | Biochemical Oxygen Demand |
| CO2 | Carbon Dioxide Uptake in Grass Plants |
| ChickWeight | Weight Versus Age of Chicks on Different Diets |
| DNase | Elisa assay of DNase |
| EuStockMarkets | Daily Closing Prices of Major European Stock Indices, 1991-1998 |
| Formaldehyde | Determination of Formaldehyde |
| HairEyeColor | Hair and Eye Color of Statistics Students |
| Harman23.cor | Harman Example 2.3 |
| Harman74.cor | Harman Example 7.4 |
| Indometh | Pharmacokinetics of Indomethacin |
| InsectSprays | Effectiveness of Insect Sprays |
| JohnsonJohnson | Quarterly Earnings per Johnson & Johnson Share |
| LakeHuron | Level of Lake Huron 1875-1972 |
| LifeCycleSavings | Intercountry Life-Cycle Savings Data |
| Loblolly | Growth of Loblolly Pine Trees |
| Nile | Flow of the River Nile |
| Orange | Growth of Orange Trees |
# kniznica datasets obsahuje databazu nazvanu CO2. Mozeme sa na nu odvolavat nasledovne, ako napr.
head(CO2) Plant Type Treatment conc uptake
1 Qn1 Quebec nonchilled 95 16.0
2 Qn1 Quebec nonchilled 175 30.4
3 Qn1 Quebec nonchilled 250 34.8
4 Qn1 Quebec nonchilled 350 37.2
5 Qn1 Quebec nonchilled 500 35.3
6 Qn1 Quebec nonchilled 675 39.2
Môžeme použiť aj databázu určenú pre ekobometriu - package Wooldridge
# install.packages("wooldridge")
library(wooldridge)
ds <- as.data.frame(utils::data(package = "wooldridge")$results)[, c("Item","Title")]
knitr::kable(head(ds, 20), col.names = c("Dataset", "Title")) %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE,
position = "center"
)| Dataset | Title |
|---|---|
| admnrev | admnrev |
| affairs | affairs |
| airfare | airfare |
| alcohol | alcohol |
| apple | apple |
| approval | approval |
| athlet1 | athlet1 |
| athlet2 | athlet2 |
| attend | attend |
| audit | audit |
| barium | barium |
| beauty | beauty |
| benefits | benefits |
| beveridge | beveridge |
| big9salary | big9salary |
| bwght | bwght |
| bwght2 | bwght2 |
| campus | campus |
| card | card |
| catholic | catholic |
Import údajov z .csv alebo .xls
Ja som si zvolil údaje z Kaggle: World Bank World Development Indicators. Na stránke sa nachádza súbor world_bank_development_indicators.csv, ktorý som si stiahol a uložil som to do zložky projektu. Ako oddeľovač prvkov sa používa čiarka. Používa sa desatinná bodka, nie čiarka. V prvom riadku sú uvedené názvy stĺpcov, ktoré neskôr budú slúžiť ako premenné. Sú už od začiatku prispôsobené na použitie ako premenné.
Potom už stačí importovať údaje do .data.frame., a to nasledovne
udaje <- read.csv2("world_bank_development_indicators.csv",
header=TRUE,sep=",",dec=".")
library(janitor)
udaje <- clean_names(udaje)
udaje <- udaje %>%
mutate(co2_per_capita = co2_emisions / population)
head(udaje) # niekolko prvych riadkov country date agricultural_land forest_land land_area
1 Afghanistan 1960-01-01 NA NA NA
2 Afghanistan 1961-01-01 57.87836 NA 652230
3 Afghanistan 1962-01-01 57.95502 NA 652230
4 Afghanistan 1963-01-01 58.03168 NA 652230
5 Afghanistan 1964-01-01 58.11600 NA 652230
6 Afghanistan 1965-01-01 58.12367 NA 652230
avg_precipitation trade_in_services control_of_corruption_estimate
1 NA NA NA
2 327 NA NA
3 327 NA NA
4 327 NA NA
5 327 NA NA
6 327 NA NA
control_of_corruption_std access_to_electricity renewvable_energy_consumption
1 NA NA NA
2 NA NA NA
3 NA NA NA
4 NA NA NA
5 NA NA NA
6 NA NA NA
electric_power_consumption co2_emisions other_greenhouse_emisions
1 NA NA NA
2 NA NA NA
3 NA NA NA
4 NA NA NA
5 NA NA NA
6 NA NA NA
population_density inflation_annual real_interest_rate
1 NA NA NA
2 13.47706 NA NA
3 13.75136 NA NA
4 14.04024 NA NA
5 14.34389 NA NA
6 14.66530 NA NA
risk_premium_on_lending research_and_development_expenditure
1 NA NA
2 NA NA
3 NA NA
4 NA NA
5 NA NA
6 NA NA
central_goverment_debt tax_revenue expense goverment_effectiveness_estimate
1 NA NA NA NA
2 NA NA NA NA
3 NA NA NA NA
4 NA NA NA NA
5 NA NA NA NA
6 NA NA NA NA
goverment_effectiveness_std human_capital_index doing_business
1 NA NA NA
2 NA NA NA
3 NA NA NA
4 NA NA NA
5 NA NA NA
6 NA NA NA
time_to_get_operation_license statistical_performance_indicators
1 NA NA
2 NA NA
3 NA NA
4 NA NA
5 NA NA
6 NA NA
individuals_using_internet logistic_performance_index military_expenditure
1 NA NA NA
2 NA NA NA
3 NA NA NA
4 NA NA NA
5 NA NA NA
6 NA NA NA
gdp_current_us political_stability_estimate political_stability_std
1 537777811 NA NA
2 548888896 NA NA
3 546666678 NA NA
4 751111191 NA NA
5 800000044 NA NA
6 1006666638 NA NA
rule_of_law_estimate rule_of_law_std regulatory_quality_estimate
1 NA NA NA
2 NA NA NA
3 NA NA NA
4 NA NA NA
5 NA NA NA
6 NA NA NA
regulatory_quality_std government_expenditure_on_education
1 NA NA
2 NA NA
3 NA NA
4 NA NA
5 NA NA
6 NA NA
government_health_expenditure multidimensional_poverty_headcount_ratio
1 NA NA
2 NA NA
3 NA NA
4 NA NA
5 NA NA
6 NA NA
gini_index birth_rate death_rate life_expectancy_at_birth population
1 NA 50.340 31.921 32.535 8622466
2 NA 50.443 31.349 33.068 8790140
3 NA 50.570 30.845 33.547 8969047
4 NA 50.703 30.359 34.016 9157465
5 NA 50.831 29.867 34.494 9355514
6 NA 50.872 29.389 34.953 9565147
rural_population voice_and_accountability_estimate
1 7898093 NA
2 8026804 NA
3 8163985 NA
4 8308019 NA
5 8458694 NA
6 8617815 NA
voice_and_accountability_std intentional_homicides co2_per_capita
1 NA NA NA
2 NA NA NA
3 NA NA NA
4 NA NA NA
5 NA NA NA
6 NA NA NA
colnames(udaje) # nazvy premennych [1] "country"
[2] "date"
[3] "agricultural_land"
[4] "forest_land"
[5] "land_area"
[6] "avg_precipitation"
[7] "trade_in_services"
[8] "control_of_corruption_estimate"
[9] "control_of_corruption_std"
[10] "access_to_electricity"
[11] "renewvable_energy_consumption"
[12] "electric_power_consumption"
[13] "co2_emisions"
[14] "other_greenhouse_emisions"
[15] "population_density"
[16] "inflation_annual"
[17] "real_interest_rate"
[18] "risk_premium_on_lending"
[19] "research_and_development_expenditure"
[20] "central_goverment_debt"
[21] "tax_revenue"
[22] "expense"
[23] "goverment_effectiveness_estimate"
[24] "goverment_effectiveness_std"
[25] "human_capital_index"
[26] "doing_business"
[27] "time_to_get_operation_license"
[28] "statistical_performance_indicators"
[29] "individuals_using_internet"
[30] "logistic_performance_index"
[31] "military_expenditure"
[32] "gdp_current_us"
[33] "political_stability_estimate"
[34] "political_stability_std"
[35] "rule_of_law_estimate"
[36] "rule_of_law_std"
[37] "regulatory_quality_estimate"
[38] "regulatory_quality_std"
[39] "government_expenditure_on_education"
[40] "government_health_expenditure"
[41] "multidimensional_poverty_headcount_ratio"
[42] "gini_index"
[43] "birth_rate"
[44] "death_rate"
[45] "life_expectancy_at_birth"
[46] "population"
[47] "rural_population"
[48] "voice_and_accountability_estimate"
[49] "voice_and_accountability_std"
[50] "intentional_homicides"
[51] "co2_per_capita"
Grafy
ggplot2 - knižnica pre grafy
Výber a následné triedenie
library(dplyr)
library(lubridate)
udaje.2013 <- udaje %>%
filter(year(date) == 2013) %>%
dplyr::select(country, renewvable_energy_consumption, co2_per_capita, government_health_expenditure, individuals_using_internet, gdp_current_us, life_expectancy_at_birth)Knižnica .ggplot2. je v súčasnosti najčastejšie používaná grafická knižnica, pričom predpripravené kódy k jednotlivým obrázkom si viete nájsť v R Graph Gallery. Tu si uvedieme jednoduchšie z nich.
Scatter plot
# Basic scatter plot
library(ggplot2)
ggplot(udaje.2013, aes(x = renewvable_energy_consumption, y = co2_per_capita)) + # specifikacia osi
geom_point() + # typ grafu - scatterplot
theme_minimal() +
labs(title = "Ekológia a spotreba čistej energie (2013)", x = "Spotreba energie z obnoviteľných zdrojov, %", y = "Emisie CO2 na obyvateľa") # oznacenie osiBoxplot
udaje %>%
filter(!is.na(co2_emisions)) %>%
summarise(min_year = min(year(date)), max_year = max(year(date))) min_year max_year
1 1990 2020
# Bar plot with grouping
library(ggplot2)
udaje %>%
filter(!is.na(co2_per_capita)) %>%
ggplot(aes(x = factor(year(date)), y = co2_per_capita)) + # specifikacia osi
geom_boxplot(fill = "lightblue", color = "darkblue") + # typ grafu - boxplot
labs( # oznacenie osi, nazov grafu
title = "Ekológia a spotreba čistej energie podľa rokov",
x = "Roky",
y = "Emisie CO2 na obyvateľa"
) +
theme_minimal() +
theme(
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)
)Základné štatistiky.
knitr - tabuľka
library(dplyr)
library(knitr)
# Summarise basic statistics
co2.stats <- udaje %>%
mutate(co2_tonnes_per_capita = (co2_emisions * 1000) / population) %>%
filter(year(date) %in% 2013:2016) %>%
group_by(Year = year(date)) %>%
summarise(
n = n(),
mean = mean(co2_tonnes_per_capita, na.rm = TRUE),
sd = sd(co2_tonnes_per_capita, na.rm = TRUE),
min = min(co2_tonnes_per_capita, na.rm = TRUE),
q25 = quantile(co2_tonnes_per_capita, 0.25, na.rm = TRUE),
median= median(co2_tonnes_per_capita, na.rm = TRUE),
q75 = quantile(co2_tonnes_per_capita, 0.75, na.rm = TRUE),
max = max(co2_tonnes_per_capita, na.rm = TRUE),
.groups = "drop"
)
# Create knitr table
kable(co2.stats, digits = 2, caption = "Basic statistics of CO2 permission capacity (2013–2016)")| Year | n | mean | sd | min | q25 | median | q75 | max |
|---|---|---|---|---|---|---|---|---|
| 2013 | 274 | 4.27 | 4.99 | 0.03 | 0.79 | 2.71 | 6.04 | 37.60 |
| 2014 | 274 | 4.19 | 4.86 | 0.03 | 0.80 | 2.86 | 5.90 | 37.11 |
| 2015 | 274 | 4.12 | 4.71 | 0.03 | 0.77 | 2.82 | 5.77 | 35.29 |
| 2016 | 274 | 4.11 | 4.63 | 0.03 | 0.75 | 2.75 | 5.83 | 33.55 |
alebo krajšie tabuľky s pomocou .kableExtra.:
library(dplyr)
library(knitr)
library(kableExtra)
# Summarise basic statistics
co2.stats <- udaje %>%
mutate(co2_tonnes_per_capita = (co2_emisions * 1000) / population) %>%
filter(year(date) %in% 2013:2016) %>%
group_by(Year = year(date)) %>%
summarise(
n = n(),
mean = mean(co2_tonnes_per_capita, na.rm = TRUE),
sd = sd(co2_tonnes_per_capita, na.rm = TRUE),
min = min(co2_tonnes_per_capita, na.rm = TRUE),
q25 = quantile(co2_tonnes_per_capita, 0.25, na.rm = TRUE),
median= median(co2_tonnes_per_capita, na.rm = TRUE),
q75 = quantile(co2_tonnes_per_capita, 0.75, na.rm = TRUE),
max = max(co2_tonnes_per_capita, na.rm = TRUE),
.groups = "drop"
)
# Create styled kableExtra table
co2.stats %>%
kable(digits = 2, caption = "Basic statistics of CO2 permission capacity (2013–2016)") %>%
kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover", "condensed")) %>%
column_spec(1, bold = TRUE) %>% # make years bold
row_spec(0, bold = TRUE, background = "#f2f2f2") %>% # style header row
add_header_above(c(" " = 2, "CO2 Statistics" = 7))| Year | n | mean | sd | min | q25 | median | q75 | max |
|---|---|---|---|---|---|---|---|---|
| 2013 | 274 | 4.27 | 4.99 | 0.03 | 0.79 | 2.71 | 6.04 | 37.60 |
| 2014 | 274 | 4.19 | 4.86 | 0.03 | 0.80 | 2.86 | 5.90 | 37.11 |
| 2015 | 274 | 4.12 | 4.71 | 0.03 | 0.77 | 2.82 | 5.77 | 35.29 |
| 2016 | 274 | 4.11 | 4.63 | 0.03 | 0.75 | 2.75 | 5.83 | 33.55 |
t-test: Porovnanie priemeru emisií CO₂ v rokoch 2000 a 2020
t.test.result <- t.test(
udaje$co2_per_capita[year(udaje$date) == 2000],
udaje$co2_per_capita[year(udaje$date) == 2020]
)
print(t.test.result)
Welch Two Sample t-test
data: udaje$co2_per_capita[year(udaje$date) == 2000] and udaje$co2_per_capita[year(udaje$date) == 2020]
t = 0.63382, df = 456.26, p-value = 0.5265
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-0.0005905411 0.0011528164
sample estimates:
mean of x mean of y
0.004048806 0.003767668
ANOVA: Comparing Reading Scores Across Programs
anova.result <- aov(co2_per_capita ~ factor(year(date)), data = udaje)
summary(anova.result) Df Sum Sq Mean Sq F value Pr(>F)
factor(year(date)) 30 0.00016 5.444e-06 0.206 1
Residuals 7377 0.19500 2.643e-05
9864 пропущенных наблюдений удалены
Linear Regression: Predicting Math Scores
model_life <- lm(
life_expectancy_at_birth ~ `government_health_expenditure` +
`individuals_using_internet` +
log(gdp_current_us),
data = udaje.2013
)
summary(model_life)
Call:
lm(formula = life_expectancy_at_birth ~ government_health_expenditure +
individuals_using_internet + log(gdp_current_us), data = udaje.2013)
Residuals:
Min 1Q Median 3Q Max
-16.6392 -2.4269 0.3231 2.7296 8.6047
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 56.46261 2.37479 23.776 < 2e-16 ***
government_health_expenditure 0.49484 0.16799 2.946 0.00356 **
individuals_using_internet 0.21179 0.01393 15.204 < 2e-16 ***
log(gdp_current_us) 0.17144 0.09676 1.772 0.07778 .
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 4.085 on 223 degrees of freedom
(47 пропущенных наблюдений удалены)
Multiple R-squared: 0.737, Adjusted R-squared: 0.7335
F-statistic: 208.3 on 3 and 223 DF, p-value: < 2.2e-16
# install.packages(c("broom", "kableExtra", "dplyr", "stringr"))
library(broom)
library(dplyr)
library(kableExtra)
library(stringr)
coef.tbl <- tidy(model_life, conf.int = TRUE) %>%
mutate(
term = dplyr::recode(term,
"(Intercept)" = "Intercept",
"government_health_expenditure" = "Government Health Expenditure (%)",
"individuals_using_internet" = "Individuals Using Internet (%)",
"log(gdp_current_us)" = "Log GDP (Current US$)"
),
stars = case_when(
p.value < 0.001 ~ "***",
p.value < 0.01 ~ "**",
p.value < 0.05 ~ "*",
p.value < 0.1 ~ "·",
TRUE ~ ""
)
) %>%
transmute(
Term = term,
Estimate = estimate,
`Std. Error` = std.error,
`t value` = statistic,
`p value` = p.value,
`95% CI` = str_c("[", round(conf.low, 3), ", ", round(conf.high, 3), "]"),
Sig = stars
)
coef.tbl %>%
kable(
digits = 3,
caption = "OLS Regression Coefficients: Determinants of Life Expectancy at Birth (2013)"
) %>%
kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover", "condensed")) %>%
column_spec(1, bold = TRUE) %>%
row_spec(0, bold = TRUE, background = "#f2f2f2") %>%
footnote(
general = "Signif. codes: *** p<0.001, ** p<0.01, * p<0.05, · p<0.1.",
threeparttable = TRUE
)| Term | Estimate | Std. Error | t value | p value | 95% CI | Sig |
|---|---|---|---|---|---|---|
| Intercept | 56.463 | 2.375 | 23.776 | 0.000 | [51.783, 61.143] | *** |
| Government Health Expenditure (%) | 0.495 | 0.168 | 2.946 | 0.004 | [0.164, 0.826] | ** |
| Individuals Using Internet (%) | 0.212 | 0.014 | 15.204 | 0.000 | [0.184, 0.239] | *** |
| Log GDP (Current US$) | 0.171 | 0.097 | 1.772 | 0.078 | [-0.019, 0.362] | · |
| Note: | ||||||
| Signif. codes: *** p<0.001, ** p<0.01, * p<0.05, · p<0.1. |
fit.tbl <- glance(model_life) %>%
transmute(
`R-squared` = r.squared,
`Adj. R-squared` = adj.r.squared,
`F-statistic` = statistic,
`F p-value` = p.value,
`AIC` = AIC,
`BIC` = BIC,
`Num. obs.` = nobs
)
fit.tbl %>%
kable(digits = 3, caption = "Model Fit Statistics (Life Expectancy Model)") %>%
kable_styling(full_width = FALSE, bootstrap_options = c("condensed"))| R-squared | Adj. R-squared | F-statistic | F p-value | AIC | BIC | Num. obs. |
|---|---|---|---|---|---|---|
| 0.737 | 0.733 | 208.318 | 0 | 1289.113 | 1306.238 | 227 |
Info zdroje pre ďalšie štúdium
R Project
- R Project Homepage - Base R downloads, news, and learning resources
Posit
- R Studio Desktop - Feature rich environment for working with data in R
- R for Data Science - Comprehensive online book
- RStudio Cheatsheets - Quick reference guides
Community Resources
- R-bloggers - Blog aggregator for R news and tutorials
- Stack Overflow - R tag - Q&A community
- rdrr.io Snippets - Test R code snippets online
- Coursera - R Programming - Online course
- DataCamp - Introduction to R - Interactive learning platform