1.创建数据集/矩阵【data.frame数据框、matrix矩阵、array数组】
代码语言:javascript复制#数据框:将字段以列合并在一起。
leadership <- data.frame(manager, date ,country, gender, age, q1,q2,q3,q4,q5, stringsAsFactors=F)
代码语言:javascript复制#矩阵:通过调整参数,控制矩阵样式。
m1 <- matrix(c(1:6),nrow=2,ncol=3,dimnames=list(c("r1","r2"),c("c1","c2","c3")))
m2 <- matrix(1:6,nrow=2) #共6个元素,分2行,每行3个元素,未指定行名和列名
m3 <- matrix(1:6,ncol=3) #共6个元素,结果与创建形式2相同m4 <- matrix(nr=2,nc=3) #未指定元素数据,默认为NA,2行3列,nr是nrow的简写,nc是ncol的简写,R能识别
代码语言:javascript复制#数组
mydata <- array(1:12,c(2,3,2),dimnames=list(c("r1","r2"),c("c1","c2","c3"),c("h1","h2"))
#myarray <- array(vector, dimensions, dimnames)
代码语言:javascript复制#factor和list#factor是numeric数值类型factor(x = character(), levels, labels = levels,exclude = NA, ordered = is.ordered(x), nmax = NA)
#注意:levels与labels的对应关系,其中levels发挥角标作用,与labels位置对应例如:
x <- c("Man", "Male", "Man", "Lady", "Female")
xf <- factor(x, levels = c("Male", "Man" , "Lady", "Female"),labels = c("Male", "Male", "Female", "Female"))
#数据列表:可用于合并多个不同类型数据字段,例如:pts <- list(x = cars[,1], y = cars[,2])
2.向数据集中增加列【transform、cbind、merge】
代码语言:javascript复制方法一:leadership <- transform(leadership,meanx= (q1 q2 q3 q4 q5)/5)
方法二:leadership$x <- c(1,1,1,1,1)
方法三:cbind(leadership,x)
方法四:merge student1<-data.frame(ID,name)student2<-data.frame(ID,score)total_student<-merge(student1,student2,by="ID")
3.向数据集中增加行【rbind】
代码语言:javascript复制方法一:leadership[6,] <- c(6,"5/1/09","US","M",25,1,1,1,1,1,1,1,1,1) #需注意变量个数相等
方法二:rbindID<-c(1,2,3)name<-c("Jame","Kevin","Sunny")student1<-data.frame(ID,name)
ID<-c(4,5,6)name<-c("Sun","Frame","Eric")student2<-data.frame(ID,name)total<-rbind(student1,student2)
4.修改数据【修改指定单元格,修改指定列,with 关联修改】
代码语言:javascript复制leadership$age[leadership$age==99] <- NA
leadership$agecat2 <- NA
leadership <- within(leadership,{
agecat2[age>75] <- "Elder"
agecat2[age>=55 & age<=75] <- "Middle Aged"
agecat2[age<55] <- "Young"})
5.修改变量名【rname】
代码语言:javascript复制library(plyr)leadership <- rename(leadership,c(manager="managerID", date="testDate"))
6.排序【order,其中默认升序,变量前加“-”代表降序】
代码语言:javascript复制leadership[order(age),]
leadership[order(gender,age),]
leadership[order(gender,-age),]
7.数据筛选【条件筛选、&、|】
代码语言:javascript复制#leadership <- data.frame(manager, date ,country, gender, age, q1,q2,q3,q4,q5, stringsAsFactors=F)
#筛选指定字段leadership[,c(6:10)]
等同:leadership[c("q1","q2","q3","q4","q5")]
等同:myvars <- paste("q",1:5,sep="")
#条件筛选(和、且)leadership[gender=='M' & age>30,]
#且subset(leadership, age>=35 | age<24, select=gender:q4) #or条件筛选 列筛选
8.抽样
代码语言:javascript复制leadership[sample(1:nrow(leadership),3,replace=F),] #replace=T说明不可以重复抽样
9.设置有效数字【digits】
代码语言:javascript复制options(digits=3)
10.【进阶】数据库相关dplyr
代码语言:javascript复制install.packages("dplyr") library(dplyr)】
dplyr包最常使用的函数主要包括以下几个:变量筛选函数:select数据筛选函数:filter排序函数:arrange变形函数:mutate汇总函数:summarize分组函数:group_by管道连接符:%>%随机抽样函数:sample_n, sample_frac