版权声明:All rights reserved by LK12, reprint please explain the source https://blog.csdn.net/qq_40527086/article/details/82891198
单模式数据结构
本学习笔记参考Andy Nicholls的R语言入门经典
载入R包
library() /require()
查看数据编码模式
mode()
查看数据类型
class()
向量(无结构)矩阵(二维)数组(多维(单一模式)
Vector
创建向量
numerciVector = c(1,2,3,4,5) #数值型向量
logicalVector = c(T,F,T,F,TRUE,FALSE) #逻辑性向量
completeVector = c(3+4i,4+3i) #复数型向量
stringVector = c('lk','lk1') #字符型向量
repeatedNumericVector = c(numerciVector,numerciVector,numerciVector) #重复产生向量
intSequence1 = 1:100/-1:1/c(0:4,5,4:0) #创建间隔为1的序列
intSequence2 = 2*1:50 #创建间隔为2的序列
sequence1 = seq(1,10,by = 0.5) #创建1-10,间隔为0.5的序列
sequence2 = seq(1,10,length = 10) #创建从1—10的10值序列
repeatedNumericVector1 = rep(numerciVector,3) #产生重复3次的numerciVector向量
repeatedStringVector1 = rep(stringVector,3)#产生重复3次的stringVector向量
rep(1:5,10)
rep(c('lk12','lk13'),c(2,3))
rep(c('lk12','lk13'),3)
rep(c('lk12','lk13'),each = 3)
如果向量中有多模式结构,R会把向量中的元素强制变成单模式
c(1,2,'lk12')
c(1,2,T,FALSE)
向量性质查询
mode(x)
class(x)
length(Vector)
为向量起名
genderFrequence = c(Female = 123, Male = 100) #赋值时起名
names(genderFrequence) #查询名字
NonenameVector = c(123,100)
names(NonenameVector) = c('Female','Male') #后起名
索引向量
x = c(1,2,3,4,5,6) #创建向量
x
x[]
x[c(1:2,5)]
x[-3]
x[c(-2,-4)]
x[x > 3]
x >= 3
x == 6
x != 5
x[x>2 & x<5]
names(x) = c('a','b','c','d','e','f')
x[c('a','c']
英文字母自带序列
letters()
LETTERS()
Matrix
矩阵创建
cbind(1:3,2:4,rep(1,3))
rbind(1:3,2:4,rep(1,3))
t(Matrix)
t(cbind(1:3,2:4,rep(1,3))) == rbind(1:3,2:4,rep(1,3))
matrix(1:12,nrow = 3)
matrix(1:12,nrow = 3,byrow = F)
矩阵的性质
X = matrix(1:12,nrow = 3,byrow = F)
mode(X)
class(X)
length(X)
dim(X)
dim(X)[1]
nrow(X)
ncol(X)
给矩阵起名
X = matrix(1:12,nrow = 3,byrow = F)
dimnames(X) = list(c('18-25','26-35','36+'),c('Lk1','Lk2','Lk3','Lk4'))
dimnames(X)
矩阵索引
X = matrix(1:12,nrow = 3,byrow = F)
X[,]
X[1,]
X[c(1,2),]
X[-1,]
X[,1]
X[,1,drop = FALSE] #保持原来维度
X[c(F,T,T),]
X[X[,1] !=2]
dimnames(X) = list(c('18-25','26-35','36+'),c('Lk1','Lk2','Lk3','Lk4'))
X[,c('Lk1','Lk2')]
Array
创建数组
aVector = c(1:12)
X = array(aVector,dim = c(3,4))
X = array(rep(aVector,3),dim = c(3,4,3))
数组属性
aVector = c(1:12)
X = array(aVector,dim = c(3,4))
mode(X)
length(X)
dim(X)
数组起名
aVector = c(1:12)
X = array(rep(aVector,3),dim = c(3,4,3))
dimnames(X) = list(letters[1:3],LETTERS[1:4],c('X1','X2','X3'))
数组索引
aVector = c(1:12)
X = array(rep(aVector,3),dim = c(3,4,3))
dimnames(X) = list(letters[1:3],LETTERS[1:4],c('X1','X2','X3'))
X[,,1]
X[-1,1:2,1:2]
Vector/Matrix/Array difference and transfer
x = 1:12 # This is a Vector
dim(x) = c(3,4) #This is a Matrix
dim(x) = c(3,2,2) #This is an Array