R

第二章

2.2数据结构

向量、矩阵、数组、数据框、列表

2.2.1向量

标量是只含有一个元素的向量。

a <- c(2:6) 等价于 a <- c(2,3,4,5,6)

2.2.2 矩阵

cells <- c(1,2,5,6)
rnames <- c("R1","R2")
cnames <- c("c1","c2")
my <- matrix(cells,nrow=2,ncol=2,byrow = TRUE,dimnames = list(rnames,cnames))

my[2,c(4,5)]  #取数

2.2.3 数组

dim1 <- c("a1","a2","a3")
dim2 <- c("b1","b2")
dim3 <- c("c1","c2","c3","c4")
z <- array(1:24,dim = c(3,2,4),dimnames = list(dim1,dim2,dim3))

2.2.4数据框

选取数据框元素

1.patientdata[1:2]

2.patientdata[c("diabetes", "status")]

3.patientdata$age

 

1.attach、detach、with

table(patientdata$diabetes, patientdata$status)

基于diabetes、status

 

不写字段

summary(mtcars$mpg)
plot(mtcars$mpg, mtcars$disp)
plot(mtcars$mpg, mtcars$wt)
改为
attach(mtcars)
summary(mpg)
plot(mpg, disp)
plot(mpg, wt)
detach(mtcars)

使用attach,如果环境中有对象了,原始的对象优先,注意masked警告

还可以使用with

with(mtcars, {
print(summary(mpg))
plot(mpg, disp)
plot(mpg, wt)
})

with只对括号内生效,with结构外使用<<,创建在全局环境中

2.实例标识符

patientdata <- data.frame(patientID, age, diabetes,
status, row.names=patientID)

2.2.5 因子

变量分为:名义型、有序型、连续型。

factor()取值范围是[1...k] ,不重复。

数值型变量用levels、labels来编码

有序性变量的设置是加个 ordered=true

2.2.6 列表

 if(FALSE){。。。。} 相当于#。。。。注释

2.3数据的输入

mydata <- data.frame(age=numeric(0),
gender=character(0), weight=numeric(0))
mydata <- edit(mydata)

mydata <- edit(mydata)  等价于 fix(mydata)

 

posted on 2018-05-14 21:42  大稀饭  阅读(97)  评论(0)    收藏  举报