knitr::opts_chunk$set(
echo = TRUE,
message = FALSE,
warning = FALSE
)
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.
Majme údaje o mojich kamarátoch, ktoré predstavujú tri premenné - iniciála mena, vek a počet koncertov, na ktorých boli:
# Working with data frames
InicialaMena <- c("A", "K", "J", "M")
Vek <- c(23,22,22,22)
PocetKoncertov <- c(4,2,2,3)
Tieto tri premenné nie sú zatiaľ nijako prepojené, predstavujú izolované stĺpce tabuľky. Do tabuľky ich spojíme nasledovne:
udaje <- data.frame(InicialaMena,Vek,PocetKoncertov)
print(udaje)
## InicialaMena Vek PocetKoncertov
## 1 A 23 4
## 2 K 22 2
## 3 J 22 2
## 4 M 22 3
Vysvetlenie: DataFrame má tri stĺpce: InicialaMena, Vek a PocetKoncertov. Niektoré operácie s údajmi organizovanými v .data.frame. sú uvedené nasledovne
print(udaje$Vek) # takto adresujeme jednotlivé premenné v data.frame
## [1] 23 22 22 22
print(mean(udaje$Vek)) # priemerny vek
## [1] 22.25
print(udaje[InicialaMena=="J",]) # adresovanie celého riadku
## InicialaMena Vek PocetKoncertov
## 3 J 22 2
print(udaje[1,]) # ina moznost adresovania celeho riadku
## InicialaMena Vek PocetKoncertov
## 1 A 23 4
print(udaje[,2:3]) # vypisanie druheho a tretieho stlpca tabulky
## Vek PocetKoncertov
## 1 23 4
## 2 22 2
## 3 22 2
## 4 22 3
print(udaje[1,2]) # vypisanie jednej bunky tabulky
## [1] 23
summary(udaje) # zakladna deskriptivna statistika celej tabulky
## InicialaMena Vek PocetKoncertov
## Length:4 Min. :22.00 Min. :2.00
## Class :character 1st Qu.:22.00 1st Qu.:2.00
## Mode :character Median :22.00 Median :2.50
## Mean :22.25 Mean :2.75
## 3rd Qu.:22.25 3rd Qu.:3.25
## Max. :23.00 Max. :4.00
Ak chceme pridať k tabuľke dodatočný stĺpec, potom to robíme nasledovne
IsliZDonutenia <- c(TRUE,FALSE,FALSE,TRUE)
udaje <- cbind(udaje,IsliZDonutenia)
print(udaje)
## InicialaMena Vek PocetKoncertov IsliZDonutenia
## 1 A 23 4 TRUE
## 2 K 22 2 FALSE
## 3 J 22 2 FALSE
## 4 M 22 3 TRUE
Ak chceme pridať riadok, potom
# New record (must match column order/types)
novy.riadok <- data.frame(InicialaMena = "Ja", Vek = 22, PocetKoncertov = 15, IsliZDonutenia = FALSE)
# Append
udaje <- rbind(udaje, novy.riadok)
print(udaje)
## InicialaMena Vek PocetKoncertov IsliZDonutenia
## 1 A 23 4 TRUE
## 2 K 22 2 FALSE
## 3 J 22 2 FALSE
## 4 M 22 3 TRUE
## 5 Ja 22 15 FALSE
library(knitr)
library(kableExtra)
kable(
udaje,
# format,
digits = 2,
# row.names = NA,
# col.names = NA,
align=c("c","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")
InicialaMena | Vek | PocetKoncertov | IsliZDonutenia |
---|---|---|---|
A | 23 | 4 | TRUE |
K | 22 | 2 | FALSE |
J | 22 | 2 | FALSE |
M | 22 | 3 | TRUE |
Ja | 22 | 15 | FALSE |
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. 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 následné triedenie
udaje %>%
filter(PocetKoncertov > 2) %>%
arrange(desc(PocetKoncertov)) %>%
kable %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE,
position = "left"
)
InicialaMena | Vek | PocetKoncertov | IsliZDonutenia |
---|---|---|---|
Ja | 22 | 15 | FALSE |
A | 23 | 4 | TRUE |
M | 22 | 3 | TRUE |
# Zoskupí and sumarizuje
udaje %>%
group_by(IsliZDonutenia) %>%
summarise(
Priem.Vek = mean(Vek),
count = n()
) %>%
kable(
caption = "Priemerny vek podľa premennej IsliZDonutenia",
col.names = c("Isli s donutenia", "Priemer vek", "Počet"),
align = "l"
) %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE,
position = "right"
)
Isli s donutenia | Priemer vek | Počet |
---|---|---|
FALSE | 22.0 | 3 |
TRUE | 22.5 | 2 |
# Vytváranie novej premennej
udaje %>%
mutate(
PojdeZnova = case_when( # vytvara novu premennu grade podla nasledovnej relacnej schemy
PocetKoncertov >= 5 ~ "Urctie",
PocetKoncertov >= 3 ~ "Mozno",
PocetKoncertov < 3 ~ "Asi nie"
),
VekPoPlnoletosti = round(Vek-18,0)
) %>%
kable %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE,
position = "center"
)
InicialaMena | Vek | PocetKoncertov | IsliZDonutenia | PojdeZnova | VekPoPlnoletosti |
---|---|---|---|---|---|
A | 23 | 4 | TRUE | Mozno | 5 |
K | 22 | 2 | FALSE | Asi nie | 4 |
J | 22 | 2 | FALSE | Asi nie | 4 |
M | 22 | 3 | TRUE | Mozno | 4 |
Ja | 22 | 15 | FALSE | Urctie | 4 |
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)
Môžeme použiť aj databázu určenú pre ekonometriu - 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 |
Pre prácu na budúcich hodinách som si vybrala databázu https://www.kaggle.com/datasets/dhruvildave/spotify-charts?resource=download , ktorá zobrazuje skladby od rôznych umelcov a ich počet streamov a umiestnenie v rebríčkoch Viral 50 a Top 200 v rôznych krajinách v rôzne dátumy od roku 2017.