R語言的數據結構

R共有6種儲存數據的對象類型

  • 向量
  • 列表
  • 數組
  • 數據框
  • 矩陣
  • 因子

R中的數據結構

向量(Vectors)

向量是用於存儲數值型、字符型或邏輯型數據的一維數組。執行組合功能的函數c()可用來創建向量。

# 創建一個向量
apple <- c('red','green',"yellow")
num <- c(12, 23, 34, 56, 78, 83)
print(apple)
print(num)

# 查看向量的類型.
print(class(apple))
[1] "red"    "green"  "yellow"
[1] 12 23 34 56 78 83
[1] "character"

** !!! 單個向量中,數據的類型必須是相同的**

# 向量元素的選取

# 與其他編程語言索引從0計數不同的是,R語言的索引從1開始計數
num[1]

# 選取多個元素
num[1:3]

# 索引前加 - 號代表除去這個元素的其他元素,可以看到結果中沒有第二個元素
apple[-2]

# 選取除了第2個和第3個元素外的其他元素
num[-(2:3)]  
12
12 23 34
'red' 'yellow'
12 56 78 83

矩陣(Matrix)

矩陣是一個二維數組,只是每個元素都擁有相同的模式(數值型、字符型或邏輯型)。可通過函數matrix創建矩陣。

# matrix(data = ,nrow = n,ncol = n,byrow = ,dimnames =list(row_vector,col_vector) )
# data包含了矩陣的元素
# nrow和ncol用以指定行和列的維數
# dimnames包含了可選的、以字符型向量表示的行名和列名
# byrow則表明矩陣應當按行填充(byrow=TRUE)還是按列填充(byrow=FALSE),默認情況下按列填充。

# Create a matrix.
M = matrix( num, nrow = 2, ncol = 3, byrow = TRUE, dimnames = list(c('人口','面積'),c('北京','廣州', '上海')))
print(M)
     北京 廣州 上海
人口   12   23   34
面積   56   78   83
M1 <- matrix(1:20, nrow=5, ncol=4)
print(M1)
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20
# 矩陣元素選取

# 選取列
M1[,2]

# 選取行
M1[1,]

# 選取單個元素
M1[3,4]

# 選取符合要求的元素
M1[M1>10]
6 7 8 9 10
1 6 11 16
18
11 12 13 14 15 16 17 18 19 20

數據框(data frame)

數據框是表格數據對象。與矩陣一樣都是二維的,但是不同的是每列可以包含不同的數據模式。 第一列可以是數字,而第二列可以是字符,第三列可以是邏輯的。它是等長度的向量的列表。

df <- data.frame(
   gender = c("Male", "Male","Female"), 
   height = c(152, 171.5, 165), 
   weight = c(81,93, 78),
   Age = c(42,38,26)
)
df
genderheightweightAge
Male 152.0 81 42
Male 171.5 93 38
Female165.0 78 26
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
patientIDagediabetesstatus
1 25 Type1 Poor
2 34 Type2 Improved
3 28 Type1 Excellent
4 52 Type1 Poor
# 索引列
print(df$gender)
print(df[,2])
print(df[1:2])
print(df[['Age']])
[1] Male   Male   Female
Levels: Female Male
[1] 152.0 171.5 165.0
  gender height
1   Male  152.0
2   Male  171.5
3 Female  165.0
[1] 42 38 26
# 索引行
print(df[2:3,])
  gender height weight Age
2   Male  171.5     93  38
3 Female  165.0     78  26
# 特定條件索引
df[df$Age > 30]
genderheightAge
Male 152.0 42
Male 171.5 38
Female165.0 26
# 索引元素
print(patientdata[1,3])   # 第一列第三行

print(df$Age[1])    # Age列第一行

print(df[[2]][1])  # 第二列第一行

print(df[['Age']][1])  # Age列第一行
[1] Type1
Levels: Type1 Type2
[1] 42
[1] 152
[1] 42
# 生成成糖尿病類型變量diabetes和病情變量status的列聯表
table(patientdata$diabetes, patientdata$status)
        Excellent Improved Poor
  Type1         1        0    2
  Type2         0        1    0

數組(Array)

雖然矩陣被限制爲二維,但數組可以具有任何數量的維度。 數組函數使用一個dim屬性創建所需的維數。 在下面的例子中,我們創建了一個包含兩個元素的數組,每個元素爲3x3個矩陣。

# Create an array.
a <- array(c('green','yellow'),dim = c(3,3,2))
print(a)
, , 1

     [,1]     [,2]     [,3]    
[1,] "green"  "yellow" "green" 
[2,] "yellow" "green"  "yellow"
[3,] "green"  "yellow" "green" 

, , 2

     [,1]     [,2]     [,3]    
[1,] "yellow" "green"  "yellow"
[2,] "green"  "yellow" "green" 
[3,] "yellow" "green"  "yellow"
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))
print(z)
, , C1

   B1 B2 B3
A1  1  3  5
A2  2  4  6

, , C2

   B1 B2 B3
A1  7  9 11
A2  8 10 12

, , C3

   B1 B2 B3
A1 13 15 17
A2 14 16 18

, , C4

   B1 B2 B3
A1 19 21 23
A2 20 22 24

數組的索引同矩陣,只不過下標從2個變成了3個,數組同矩陣一樣,數據類型必須一樣

因子(Factors)

我們都知道,變量的類型可以分爲如下幾種

  • 類別變量(定性變量)
    • 無序類別變量(名義值):類別無法排序,沒有順序關係,比如行業類別,性別
    • 有序類別變量(順序值):類別之間有順序關係,比如等級,評價‘差’,‘一般’,‘很好’
  • 數值變量(定量變量)
    • 離散變量(有限值): 只能去有限個值的變量,可以一一列舉。
    • 連續變量(無限值):在一個或多個區間內取任何值,連續不斷不可一一列舉,比如溫度,身高。

類別變量在R中被稱爲因子,函數factor()以一個整數向量的形式存儲類別值,整數的取值範圍是[1-k ](其中k 是名義型變量中唯一值的個數),同時一個由字符串(原始值)組成的內部向量將映射到這些整數上。這種做法類似於python特徵分子中的將類別變量dummy化

對於有序變量,我們還可以指定變量對應的編碼,使編碼與邏輯順序相一致,比如low,mid,high對應1,2,3

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)  # order=TRUE R將此變量當做有序變量對待
patientdata <- data.frame(patientID, age, diabetes, status)
str(patientdata)   # 數據的信息,相當於pandas中的info
summary(patientdata)  # 描述性統計
# 可以看到,描述性統計中,R對數值型分析了最大最小值等,而對因子採用了頻數統計。
'data.frame':	4 obs. of  4 variables:
 $ patientID: num  1 2 3 4
 $ age      : num  25 34 28 52
 $ diabetes : Factor w/ 2 levels "Type1","Type2": 1 2 1 1
 $ status   : Ord.factor w/ 3 levels "Excellent"<"Improved"<..: 3 2 1 3



   patientID         age         diabetes       status 
 Min.   :1.00   Min.   :25.00   Type1:3   Excellent:1  
 1st Qu.:1.75   1st Qu.:27.25   Type2:1   Improved :1  
 Median :2.50   Median :31.00             Poor     :2  
 Mean   :2.50   Mean   :34.75                          
 3rd Qu.:3.25   3rd Qu.:38.50                          
 Max.   :4.00   Max.   :52.00                          
# 如果變量的默認順序不是按照邏輯順序排列的,比如status如果是按照improved,poor,excellent排列,
# 那麼默認的順序就無法代表真實邏輯順序。
# 因此,可以添加levels變量
status <- factor(status,order=TRUE,levels = c("poor", "improved", "excellent"))
# 這樣就相當於指定了順序,任何在數據中出現而未在參數中列舉的數據都將被設爲缺失值

列表

R中的列表比較像python中的列表,列表中的元素可以是單個字符,數值,也可以是向量,矩陣,數組等
列表就是一些對象的有序集合

# Create a list.
list1 <- list(c(2,5,3),21.3,sin)

# Print the list.
print(list1)
[[1]]
[1] 2 5 3

[[2]]
[1] 21.3

[[3]]
function (x)  .Primitive("sin")
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)
print(mylistlist)
$title
[1] "My First List"

$ages
[1] 25 26 18 39

[[3]]
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10

[[4]]
[1] "one"   "two"   "three"
mylist[['ages']]  # 輸出ages
mylist[[2]]   # 輸出第二個元素
25 26 18 39
25 26 18 39
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章