1,创建向量
a<-c(1,2,5,3,6,-2,4)
2,查找元素
a[c(2,4)]
3,创建矩阵
y<- matrix(1:20,nrow=5,ncol=4)
cells <- c(1,26,24,68)
> rnames <-c("R1","R2")
> cnames <-c("c1","c2")
> mymatrix<- matrix(cells,nrow=2,ncol=2,byrow=TRUE,dimnames=list(rnames,cnames))
> mymatrix
结果:
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
> cells <- c(1,26,24,68)
> rnames <-c("R1","R2")
> cnames <-c("c1","c2")
> mymatrix<- matrix(cells,nrow=2,ncol=2,byrow=TRUE,dimnames=list(rnames,cnames))
> mymatrix
结果:
c1 c2
R1 1 26
R2 24 68
按行填充:注意默认按行填充,将TRUE改成FALSE就变成了按列填充
x<- matrix(1:10,nrow=2,ncol=5,byrow=TRUE)
三维数组:
dim1<-c("A1","A2")
> dim2<-c("B1","B2","B3")
> dim3<-c("C1","C2","C3","C4")
> z<-array(1:24,c(2,3,4),dimnames=list(dim1,dim2,dim3))
数据框:每列可以存放不同类型的数据
patientID<- c(1,2,3,4)
> age<- c(25,34,28,52)
diabetes<- c("Typel","Type2","Type1","Type2")
> status<-c("Poor","Improved","Excellent","Poor")
> patientdata<-data.frame(patientID,age,diabetes,status)
关联两个属性:
table(patientdata$diabetes,patientdata$status)
Excellent Improved Poor
Type1 1 0 0
Type2 0 1 1
Typel 0 0 1
绘出散列图:
plot(mtcars$mpg,mtcars$disp)
函数 factor() 以一个整数向量的形式存储类别值,整数的取值范围是[1... k ](其中k 是名义
型变量中唯一值的个数),同时一个由字符串(原始值)组成的内部向量将映射到这些整数上。
status<- c("Poor","Improved", "Excellent", "Poor")
status<- factor(status,order=TURE)
显示对象结构:
str(patientdata)
显示对象统计概要:
summary(patientdata)
列表:列表里存的是object,可以是任意的数据结构
> g<-"My First List"
> h<- c(25,26,18,39)
> j<- matrix(1:10,nrow=5,ncol=2)
> k<- c("one","tow","three")
> mylist<- list(title=g,ages=h,j,k)
> mylist
$title
[1] "My First List"
$ages
[1] 25 26 18 39
[[3]]
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
[[4]]
[1] "one" "tow" "three"
输出该数组中的第二对象:
mylist[[2]] //按顺序
mylist[["ages"]] //按给定的名字
从键盘输入数据;
mydata <- data.frame(age=numeric(0),
+ gender=character(0),weight=numeric(0))
> mydata<- edit(mydata)
从表格中读入数据:主要默认的路径是工作目录:
grades<- read.table("StudentMessage.csv",header=TRUE,sep=",",
+ row.names="STUDENTID")
> grades
SEX AGE
1 m 18
2 f 35
3 m 19
4 f 35
下载的二进制程序包在
C:\Users\Administrator\AppData\Local\Temp\Rtmps7rFS7\downloaded_packages里
从excel导入数据:注意只能在32位的机器运行,导入数据前还需要,下载包,进入包
install.packages("RODBC")
library(RODBC)
channel<-odbcConnectExcel("nyfile.xls")