Tutoriál R/Matice

Z WikiSkript

Matice je dvojrozměrným polem, které obsahuje prvky stejného datového typu, např.

# Matice se 4 řádky obsahující čísla od 1 do 12
matrix(1:12, byrow = TRUE, nrow = 4)


Tržby v kinech trilogie "Pán prstenů" (v milionech dolarů)

  • The Lord of the Rings: The Fellowship of the Ring - 313.36 us, 558.14 non-us
  • The Lord of the Rings: The Two Towers - 339.79 us, 586.21 non-us
  • The Lord of the Rings: The Return of the King - 377.03 us, 742.87 non-us


Vytvoření vektorů pro jednotlivé filmy a jejich spojení do matice

lotr1 <- c(313.36, 558.14)
lotr2 <- c(339.79, 586.21)
lotr3 <- c(377.03, 742.87)
vektor_trzeb <- c(lotr1, lotr2, lotr3)
lotr <- matrix(vektor_trzeb, byrow = TRUE, nrow = 3)

# Pojmenování matice
region <- c("US", "non-US")
nazvy <- c("The Lord of the Rings: The Fellowship of the Ring", "The Lord of the Rings: The Two Towers", "The Lord of the Rings: The Return of the King")
colnames(lotr) <- region
rownames(lotr) <- nazvy

# Zobrazení matice
lotr

Výpočet celosvětových tržeb

# Zkrácený způsob vytvoření matice z předchozího příkladu
vektor_trzeb <- c(313.36, 558.14, 339.79, 586.21, 377.03, 742.87)
lotr <- matrix(vektor_trzeb, nrow = 3, byrow = TRUE,
                dimnames = list(c("The Lord of the Rings: The Fellowship of the Ring",
				                  "The Lord of the Rings: The Two Towers",
								  "The Lord of the Rings: The Return of the King"),
                                c("US", "non-US")
							)
)

# Vektor celosvětových tržeb
svet <- rowSums(lotr)

# Přidání sloupce s celosvětovými tržbami do matice
lotr_svet <- cbind(lotr, svet)


Přidání Hobbita k trilogii Pán Prstenů

# Vytvoření matice s Hobbitem
vektor_trzeb <- c(303, 718.1, 258.37, 700.03, 255.12, 700.88)
hobbit <- matrix(vektor_trzeb, nrow = 3, byrow = TRUE,
                dimnames = list(c("The Hobbit: An Unexpected Journey",
				                  "The Hobbit: The Desolation od Smaug",
								  "The Hobbit: The Battle of the Five Armies"),
                                c("US", "non-US")
							)
)

# Spojení matic lotr a hobbit
stredozem <- rbind(lotr, hobbit)


Přehledy, výbery dat, statistiky

# Celkové příjmy obou trilogií rozdělené na US a non-US
celkove_trzby <- colSums(stredozem) # vektor
celkove_trzby # vytiskneme

# neamerické tržby
non_us_trzby <- stredozem[, 2]

# Průměrná tržba
mean(non_us_trzby)

# Průměr pro první 2 filmy (non-US)
non_us_vyber <- stredozem[1:2, 2]
mean(non_us_vyber)

# Odhad počtu návštěvníků za předpokladu, že průměrná cena lístku je 5$
navstevnici <- stredozem/5
navstevnici

# Návštěvnící v US
navstevnici_us <- navstevnici[, 1]

# Průměrný počet US návštěvníků
mean(navstevnici_us)