常見的數據結構
- 向量 c() # 一維
- 矩陣 matrix() # 二維
- 數組 array() # 多維
- 因子factor()
- 列表list()
- 數據框 data.frame()
常見的數據類型
- integer 整型
- character 字符型
- numeric 數值型(double)
- logical 邏輯型
- NULL
- NA missing value
向量
name = c("li", "shi", "wu", "zhang", "feng")
typeof(name) # "character"
print(name)
id = c(1, 2, 3, 4, 5, 6)
typeof(id) # "double"
cloth = c(FALSE, TRUE, FALSE, TRUE, FALSE, FALSE)
typeof(cloth) # "logical"
cloth[1] # FALSE
id[2:5] # 2 3 4 5
name[-2] # "li" "wu" "zhang" "feng" 刪除2對應的元素
name[-2:-3] # "li" "zhang" "feng" 刪除2到3對應的元素
name[c(F,T,F,T,F,T)] # "shi" "zhang" NA 返回爲T對應的元素,第六個沒有元素返回來NA
matrix矩陣
functyions:
- matrix()
- ncol()
- nrow()
- rownames()
- colnames()
x=matrix(c(1:9),ncol=3,nrow=3)
image.png
rownames(x)=c("A","B","C")
colnames(x)=c("C","D","E")
image.png
x["A", "C"] # 1
x[1, 1] # 1
ncol(x) # 3
nrow(x) # 3
dim(x) # 3 3
array數組
xx = array(1:24, c(3, 4, 2)) # 生成3×4×2維的數組
yy = array(1:36, c(2, 3, 3, 2)) # 生成2×3×3×2維的數組
xx=1:24 # 對xx重新賦值,生成1-24排列的NULL維數組
dim(xx) = c(3, 4, 2) # 對xx的維度調整,把上面的NULL維度改成3×4×2維度的數組
zz = 1:10 #同理生成1-10的NULL維數組
dim(zz) = c(2, 5) # 維度調整
dim(xx) # 沒有等號就是返回對應變量的維度值
dim(yy)
dim(zz)
factor因子
Dragon_gender =factor(c("female","male","male","male","male","female"))
image.png
Dragon_size=factor(c("L","XL","XL","XXL","XXXL","L"),levels=c("S","M","L","XL","XXL","XXXL"))
image.png
list列表
Dragon=list(name=Dragon_name,id=Dragon_id,cloth=Dragon_cloth,gender=Dragon_gender,size=Dragon_size) #直接命名
Dragon
image.png
names(Dragon) # 輸出name,id, cloth, gender, size
length(Dragon) # 5
Dragon=list(Dragon_name, Dragon_id, Dragon_cloth, Dragon_gender,Dragon_size)
print(Dragon) #輸出自動數字編碼的結果
image.png
names(Dragon)= c("name", "id", "cloth", "gender", "size") #爲編碼命名
Dragon$note=c(9,9) #新增加note成員
# 另一種生成list方法
> Dragon = list()
> Dragon[[1]] = Dragon_name
> Dragon[[2]] = Dragon_id
> Dragon[[3]] = Dragon_cloth
> Dragon[[4]] = Dragon_gender
> Dragon[[5]] = Dragon_size
> names(Dragon)=c("name", "id", "cloth", "gender", "size")
> Dragon
訪問數據
Dragon[1] # 帶內name
Dragon[[1]] # name的內部數據
Dragon[[1]][4] # name的內部數據的第四個元素
Dragon$size
Dragon["id"]
Dragon[1:2]
Dragon[c("name", "id")]
image.png
image.png
data.frame
- 相同的數據類型
- 唯一的行或者列名字(rownames, colnames)
- data.frame的行是一個data.frame
- as.data.frame(****) list matrix等可以通過它專程data.frame
FraDragon = data.frame(name=Dragon_name,id=Dragon_id,cloth=Dragon_cloth,gender=Dragon_gender, size=Dragon_size)
image.png
names(FraDragon)
out:[1] "name" "id" "cloth" "gender" "size"
rownames(FraDragon)= FraDragon$name
image.png
colnames(FraDragon)
out:[1] "name" "id" "cloth" "gender" "size"
FraDragon=FraDragon[, -1] # 刪除第一列
FraDragon["li",] # 查找行爲li,列爲所有
FraDragon[,"size"] # 查找行爲所有,列爲size
FraDragon["li","size"] # 查找行爲li,列爲size
FraDragon=as.data.frame(Dragon) # 把list類型轉成data.frame類型