常见的数据结构
- 向量 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)

rownames(x)=c("A","B","C")
colnames(x)=c("C","D","E")

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"))

Dragon_size=factor(c("L","XL","XL","XXL","XXXL","L"),levels=c("S","M","L","XL","XXL","XXXL"))

list列表
Dragon=list(name=Dragon_name,id=Dragon_id,cloth=Dragon_cloth,gender=Dragon_gender,size=Dragon_size) #直接命名
Dragon

names(Dragon) # 输出name,id, cloth, gender, size
length(Dragon) # 5
Dragon=list(Dragon_name, Dragon_id, Dragon_cloth, Dragon_gender,Dragon_size)
print(Dragon) #输出自动数字编码的结果

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")]


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)

names(FraDragon)
out:[1] "name" "id" "cloth" "gender" "size"
rownames(FraDragon)= FraDragon$name

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类型
网友评论