# 第2章
# 矩阵 matrix
# 很多教程、推文都说matrix不好用,但是学的时候还是掌握的扎实一些哈
[AppleScript] 纯文本查看 复制代码 mymatrix <- matrix() # 创建矩阵,默认情况下,按列填充,即byrow = F
# 示例
[AppleScript] 纯文本查看 复制代码 y <- matrix(1:20, nrow = 5, ncol = 4)
y
cells <- c(1, 26, 24, 68)
rnames <- c('R1', 'R2')
cnames <- c('C1', 'C2')
mymatrix <- matrix(cells, nrow = 2, ncol = 2, byrow = 2,
dimnames = list(rnames, cnames))
mymatrix
# 数组 array
[AppleScript] 纯文本查看 复制代码 myarrar <- array(vector, dimensions, dimnames)
# 示例-创建一个三维数组
[AppleScript] 纯文本查看 复制代码 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))
z
# 数据框——最长处理的数据结构
[AppleScript] 纯文本查看 复制代码 mydata <- data.frame(col1, col2, col3,...)
# 列向量col1, col2, col3等可为任何类型(字符型、数值型或逻辑型),包罗万象~
# 示例
[AppleScript] 纯文本查看 复制代码 patientID <- c(1, 2, 3, 4)
age <- c(25, 34, 28, 52)
diabetes <- c('type1', 'type2', 'type1', 'type1')
status <- c('poor', 'improved', 'excellent', 'poor')
patientdata <- data.frame(patientID, age, diabetes, status)
patientdata
# 选取数据框中元素
[AppleScript] 纯文本查看 复制代码 patientdata[1:2]
patientdata[c('patientID', 'status')]
patientdata$patientID # $被用来选取一个给定数据框中的某个特定变量
## 每个变量前都需键入patientdata,是非常麻烦的,可以使用一些函数,简化代码
# attach()、 detach()
[AppleScript] 纯文本查看 复制代码 attach(mtcars)
summary(mpg)
summary(disp)
detach(mtcars)
summary(mpg)
# with()
[AppleScript] 纯文本查看 复制代码 with(mtcars,{
print(summary(mpg))
plot(mpg, disp)
plot(mpg, wt)
})
# with()的局限在于其赋值仅在此函数的括号内生效
# 如需创建在with()结构以外存在的变量,使用特殊赋值符 <<-替代 标准赋值符<-即可
# 因子
## 变量可归结为 名义型、有序型或连续型变量
# 连续型变量可呈现为某个范围内的任意值,并同时表示了顺序和数量
# 类别(名义型)变量和有序类别(有序型)变量称为因子
# 要表示有序型变量,需要为函数factor()指定参数ordered = T;对于字符型向量,因子的水平默认依字母顺序创建
# 可以通过levels选项来覆盖默认排序
# 示例
[AppleScript] 纯文本查看 复制代码 status <- factor(status, order = T,
levels = c('poor', 'improved', 'excellent'))#此时,poor=1,improved=2,excellent=3
# 示例-因子的使用
[AppleScript] 纯文本查看 复制代码 patientID <- c(1, 2, 3, 4)
age <- c(25, 34, 28, 52)
diabetes <- c('type1', 'type2', 'type1', 'type1')
status <- c('poor', 'improved', 'excellent', 'poor')
status <- factor(status, order = T)
diabetes <- factor(diabetes)
patientdata <- data.frame(patientID, age, diabetes, status)
patientdata
str(patientdata)
summary(patientdata)
# 函数read.table()的选项
sep #分开数据值的分隔符,默认为sep = " "
na.strings # 可选的用于表示缺失值的字符向量,如 na.strings =c('-9', '?')把-9和?读取为NA
quote # 用于对有特殊字符的字符串划定界限的字符串。默认值为双引号(")或单引号(')
|