- 數(shù)據(jù)集的概念
數(shù)據(jù)集通常是由數(shù)據(jù)構(gòu)成的一個(gè)矩形數(shù)組羹呵,行表示觀測(cè),列表示變量书劝。不同的行業(yè)對(duì)于數(shù)據(jù)集的行和列叫法不同损痰。統(tǒng)計(jì)學(xué)家稱(chēng)它們?yōu)橛^測(cè)(observation)和變量(variable),數(shù)據(jù)庫(kù)分析師則稱(chēng)其為記錄(record)和字段(field),數(shù)據(jù)挖掘/機(jī)器學(xué)習(xí)學(xué)科的研究者則把它們叫做示例(example)和屬性(attribute)谈飒。
R可以處理的數(shù)據(jù)類(lèi)型(模式)包括數(shù)值型岂座、字符型、邏輯型(TRUE/FALSE)杭措、復(fù)數(shù)型(虛數(shù))和原生型(字節(jié))费什。
- 數(shù)據(jù)結(jié)構(gòu)
R擁有許多用于存儲(chǔ)數(shù)據(jù)的對(duì)象類(lèi)型,包括標(biāo)量手素、向量鸳址、矩陣、數(shù)組泉懦、數(shù)據(jù)框和列表稿黍。
向量:
a <- c(l, 2, 5, 3, 6, -2, 4)
b <- c("one", "two", “three")
c <- c(TRUE, TRUE, TRUE, FALSE, TRUE, FALSE)
a是數(shù)值型向量,b是字符型向量祠斧,而c是邏輯型向量闻察。a[c(2, 4)]用于訪問(wèn)向量a中的第二個(gè)和第四個(gè)元素a <- c(2:6)等價(jià)于a <- c(2, 3, 4, 5, 6)
- 矩陣
矩陣是一個(gè)二維數(shù)組,只是每個(gè)元素都擁有相同的模式(數(shù)值型琢锋、字符型或邏輯型)
y <- matrix(1:20, nrow = 5, ncol = 4)
y
cells <- c(1, 26, 24, 68)
rnames <- c("R1", "R2")
cnames <- c("C1", "C2")
mymatrix <- matrix(cells, nrow = 2, ncol = 2, byrow = TRUE,
dimnames = list(rnames, cnames))
mymatrix
mymatrix <- matrix(cells, nrow = 2, ncol = 2, byrow = FALSE,
dimnames = list(rnames, cnames))
mymatrix
- 數(shù)組
數(shù)組(array)與矩陣類(lèi)似辕漂,但是維度可以大于2。數(shù)組可通過(guò)array函數(shù)創(chuàng)建
dim1 <- c("A1", "A2")
dim2 <- c("B1", "B2", "B3")
dim3 <- c("C1", "C2", "C3", "C4")
z <- array(1:24, c(2, 3, 4), dimnames = list(dim1,
dim2, dim3))
z
- 數(shù)據(jù)框
由于不同的列可以包含不同模式(數(shù)值型吴超、字符型等)的數(shù)據(jù)钉嘹,數(shù)據(jù)框的概念較矩陣來(lái)說(shuō)更為一般。
patientID <- c(1, 2, 3, 4)
age <- c(25, 34, 28, 52)
diabetes <- c("Type1", "Type2", "Type1", "Type1")
status <- c("Poor", "Improved", "Excellent", "Poor")
patientdata <- data.frame(patientID, age, diabetes,
status)
patientdata
選取數(shù)據(jù)框中的元素
patientdata[1:2]
patientdata[c("diabetes", "status")]
patientdata$age
- 因子
類(lèi)別(名義型)變量和有序類(lèi)別(有序型)變量在R中稱(chēng)為因子(factor)鲸阻。因子在R中非常重
要跋涣,因?yàn)樗鼪Q定了數(shù)據(jù)的分析方式以及如何進(jìn)行視覺(jué)呈現(xiàn)。
patientID <- c(1, 2, 3, 4)
age <- c(25, 34, 28, 52)
diabetes <- c("Type1", "Type2", "Type1", "Type1")
status <- c("Poor", "Improved", "Excellent", "Poor")
diabetes <- factor(diabetes)
status <- factor(status, order = TRUE)
patientdata <- data.frame(patientID, age, diabetes,
status)
str(patientdata)
summary(patientdata)
- 列表
列表(list)是R的數(shù)據(jù)類(lèi)型中最為復(fù)雜的一種鸟悴。一般來(lái)說(shuō)陈辱,列表就是一些對(duì)象(或成分,component)的有序集合细诸。列表允許你整合若干(可能無(wú)關(guān)的)對(duì)象到單個(gè)對(duì)象名下沛贪。
g <- "My First List"
h <- c(25, 26, 18, 39)
j <- matrix(1:10, nrow = 5)
k <- c("one", "two", "three")
mylist <- list(title = g, ages = h, j, k)
mylist