#数据框
#创建数据框
stu.name <-c(“xinyu” , “anqi”)
stu.id <- c (1001,1002)
stu.info <- data.frame (stu.name,stu.id) ; stu.info
str (stu.info)
#访问
stu.infoKaTeX parse error: Expected 'EOF', got '#' at position 36: …] stu.info[1,] #̲添加新列 stu.infoage <- c(16,19);stu.info
#查询
stu.info[which(stu.info
a
g
e
>
=
16
)
,
]
s
t
u
.
i
n
f
o
[
s
t
u
.
i
n
f
o
age>=16),] stu.info[stu.info
age>=16),]stu.info[stu.infoage>=16,]
#矩阵转数据框
mat <-matrix(1:12,nrow=3);mat
mat.df<-as.data.frame (mat);mat.df
#列表的高级操作
#merge
stu.id.math <- c (1001,1003)
stu.math.score <-c(89,90)
stu.math.df <- data.frame(stu.id.math,stu.math.score);stu.math.df
?merge
merge (stu.info,stu.math.df,by.x = “stu.id”,by.y = “stu.id.math”)
#合并
#cbind, rbind
stu.info
new.stu <- data.frame(list(stu.name=“xiaohua”,stu.id=1004,age=19));new.stu
stu.info <- rbind(stu.info, new.stu) ;stu.info
python.score <- c(99,100,100)
stu.info <-cbind (stu.info, python.score) ; stu.info
r.score <- c(98,99,100)
stu.info <-cbind (stu.info,r.score);stu.info
lapply(stu.info,max)
lapply(stu.info[3 :ncol(stu.info)], max)
sapply(stu.info[3: ncol (stu.info)], max)
#因子
sex <-c(1,2);sex
#创建因子
sex.f <- factor (sex);sex.f
str (sex.f)
stu.sex <- sample(1:2,10,replace = T); stu.sex
stu.sex.f<-factor(stu.sex); stu.sex.f
stu.sex.f<- factor(stu.sex, levels = c(1,2));stu.sex.f
中
stu.sex.f<- factor(stu.sex,levels = c(1,2),labels = c(“E”,“M”));stu.sex.f
stu.sex.v<- as.vector(stu.sex.f);stu.sex.v
#有序因子
stu.sex.ord <- ordered(stu.sex,levels = c(1,2));stu.sex.ord
stu.sex.ord <- ordered(stu.sex,levels = c(2,1));stu.sex.ord
#cut函数
stu.r.score <- c(60,sample(60:100,8,replace = T),100);stu.r.score
stu.r.score.level <- cut(stu.r.score,breaks = 4);stu.r.score.level
#tapply()函数
tapply(stu.r.score,stu.sex, mean)