部分内容参见:生信技能树 课程
image.png
matrix(1:9, byrow = TRUE, nrow = 3)
★1)1:9 表示矩阵行或列的元素信息,例设定为1到9;2)byrow 表示矩阵是按照何种排列,TRUE 为行,False 为列;默认列。3)nrow 表示每行元素数。返回结果”
> x <- sample(1:100, 24)
> x
[1] 43 87 22 59 23 1 19 36 92 70 55 3 25 15 66 49 96 26 17 5 44 38
[23] 13 20
> matrix(x, nrow=6)
[,1] [,2] [,3] [,4]
[1,] 43 19 25 17
[2,] 87 36 15 5
[3,] 22 92 66 44
[4,] 59 70 49 38
[5,] 23 55 96 13
[6,] 1 3 26 20
若为按列 排列
matrix(1:12, byrow = FALSE, ncol = 3)
'''
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
'''
t(x) 使矩阵转置,即行内容变列,列内容变行。
定义某个矩阵
star_wars_matrix <- matrix(1:6, nrow = 3, byrow = TRUE)
# 按行排列,3行6个数字,2列。
定义行和列
region <- c("US", "non-US")
titles <- c("A New Hope", "The Empire Strikes Back", "Return of the Jedi")
命名行&列
colnames(star_wars_matrix) <- region
# 命名列
rownames(star_wars_matrix) <- titles
# 命名行
输出
star_wars_matrix
使用cbind() 。向量包含的元素数值需等于矩阵行数。
big_matrix <- cbind(matrix1, matrix2, vector1 ...)
使用rbind(),操作同cbind() 加和 colSums() 或 rowSums()
matrix[x, y] ,x表示行,y表示列
martix[1:2,2:3]
# 选取1、2行的第2与3列的元素。
# 返回的也是一个向量类型的值。
'''
non-US worldwide_vector
A New Hope 314.4 775.398
The Empire Strikes Back 247.9 538.375
'''
矩阵最长使用的可视化方式便是热图。
一个合适表格就和问卷一样,是包含不同类型的数据的。但需要注意的是,数据框的每一列只 包含一种数据类型 ,也就是说每一列如果单独提取出来,都是一个向量。比如
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3
Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3
Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3
Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4
Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4
Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2
AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2
Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4
Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4
Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8
Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2
如同一个问卷一样。
★'Are you married?' or 'yes/no' questions (logical) 'How old are you?' (numeric) 'What is your opinion on this product?' or other 'open-ended' questions (character) ”
options(stringsAsFactors = F)
,通常处理df 数据开头会写上(R4.0前版本),使得R不会默认将字符串处理为因子。
image.png
as.data.frame(matrix),可以将矩阵数据转为数据框。
通过head()
与tail()
快速查看,默认提取前六行。head(df, n) 设定参数n 调整查看n行。
可以通过str() 快速了解数据集的结构信息。
★1)数据集中的observation数目。通常也就是行数。2)变量数目。通常也是列数。3)变量的数目与类型。4)前10个observation 的信息。 ”
dim(df)
返回df 几行几列。nrow(df)
, ncol(df)
,分别返回行与列。
rownames(df), colnames(df),返回行名与列名。
本质就是不同类型向量的排列组合。
首先构建vectors。
name <- c("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune")
type <- c("Terrestrial planet", "Terrestrial planet", "Terrestrial planet",
"Terrestrial planet", "Gas giant", "Gas giant", "Gas giant", "Gas giant")
diameter <- c(0.382, 0.949, 1, 0.532, 11.209, 9.449, 4.007, 3.883)
rotation <- c(58.64, -243.02, 1, 1.03, 0.41, 0.43, -0.72, 0.67)
rings <- c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)
将不同的vctors 拼接起来。
planets_df <- data.frame(name, type, diameter, rotation, rings)
显示
> planets_df
name type diameter rotation rings
1 Mercury Terrestrial planet 0.382 58.64 FALSE
2 Venus Terrestrial planet 0.949 -243.02 FALSE
3 Earth Terrestrial planet 1.000 1.00 FALSE
4 Mars Terrestrial planet 0.532 1.03 FALSE
5 Jupiter Gas giant 11.209 0.41 TRUE
6 Saturn Gas giant 9.449 0.43 TRUE
7 Uranus Gas giant 4.007 -0.72 TRUE
8 Neptune Gas giant 3.883 0.67 TRUE
还可以从外部读取df <- read.csv('xxx.csv')
。
跟matrix 类似。ps:其实就完全可以将data frame 理解为一个包含不同类型数据的matrix。
不同之处在于,frame work 可以对行和列进行定义(分类函数)。所以可以借助于变量名查询(行名或列名)。
planets_df[1:5,"diameter"]
通过$
可以直接获取分类变量下的全部信息。
rings_vector <- planets_df$rings
将 rings 列下的全部元素给新的向量
通过筛选分类下的布尔型数据,可以针对该数据筛选出目标数据。如找出所有带有rings 的planet。空着的列或行就表示全选。
planets_df[rings_vector,]
# 列出所有符合TRUE的planet
planets_df[rings_vector,"name"]
# 列出所有符合TRUE的行星name
选取双行双列
df[c(1,3),1:2]
可以直接将提取的列或行直接按照向量的用法进行条件取值。
test[test$sample3>0,]
也可以使用函数 subset
subset(frame_name, condition)
subset(planets_df, subset = diameter < 1)
# 获得直径小于1的变量
和向量是一样的,也就是选择+赋值。
当通过名称对数据框进行选择的子集不存在时,R会帮我们创建一个新的内容。
order() 会将其中的元素按照大小顺序排列,并按照大小顺序返回元素所在的位置数据。
> a <- c(100, 10, 1000)
> order(a)
[1] 2 1 3
na.omit(df)
,直接将含有缺失值的行去除。
cbind() 列连接(行需相同), rbind() 行连接(列需相同)。
如果想要连接行列数目并不相同数据库,可以使用 merge
。
如果有列不同的,可以将参数by 改为by.x =, by.y =
参见:https://www.math.pku.edu.cn/teachers/lidf/docs/Rbook/html/_Rbook/prog-type-df.html
tibble类型是一种改进的数据框类型的数据,可以通过readr 包实现读取。
library(tibble)
library(readr)
t.class <- read_csv("class.csv")
## Parsed with column specification:
## cols(
## name = col_character(),
## sex = col_character(),
## age = col_double(),
## height = col_double(),
## weight = col_double()
## )
tibble类型的类属依次为tbl_df, tbl, data.frame,用as_tibble()可以将一个数据框转换为tibble,或者直接通过tibble 像创建数据框般创建tibble 数据框:
t.bp <- tibble(
`序号`=c(1,5,6,9,10,15),
`收缩压`=c(145, 110, "未测", 150, "拒绝", 115))
t.bp
我们可以用对数据框的相同操作来处理tibble 类型的数据。
除此之外,tibble 非常喜欢csv 数据,因此也可以像创建csv 数据般,直接通过tribble 创建:
t.bp2 <- tribble(
~`序号`,~`收缩压`,
1,145,
5,110,
6,NA,
9,150,
10,NA,
15,115
)
t.bp2
## # A tibble: 6 x 2
## 序号 收缩压
## <dbl> <dbl>
## 1 1 145
## 2 5 110
## 3 6 NA
## 4 9 150
## 5 10 NA
## 6 15 115
另外,tidyr::expand_grid()
函数提供了另外一种可能,可以通过指定n 个分组,细分出多个因素完全搭配并重复的表格,比如:
d4 <- tidyr::expand_grid(
group=1:3,
subgroup=1:2,
obs=1:2)
print(d4)
## # A tibble: 12 x 3
## group subgroup obs
## <int> <int> <int>
## 1 1 1 1
## 2 1 1 2
## 3 1 2 1
## 4 1 2 2
## 5 2 1 1
## 6 2 1 2
## 7 2 2 1
## 8 2 2 2
## 9 3 1 1
## 10 3 1 2
## 11 3 2 1
## 12 3 2 2
结果的数据框d有三个变量: group是大组,共分3个大组,每组4个观测;subgroup是子组,在每个大组内分为2个子组,每个子组2个观测。共有个12 观测(行)。
另外,tibble类型允许其中的列是列表类型, 这样, 该列的每个元素就可以是复杂类型, 比如建模结果(列表), 元素之间可以保存不等长的值。如:
tibble(x = 1:3,
y = list(1, 1:2, 1:3))
## # A tibble: 3 x 2
## x y
## <int> <list>
## 1 1 <dbl [1]>
## 2 2 <int [2]>
## 3 3 <int [3]>
★The term factor refers to a statistical data type used to store categorical variables. The difference between a categorical variable and a continuous variable is that a categorical variable can belong to a limited number of categories. A continuous variable, on the other hand, can correspond to an infinite number of values. ”
factor因子 用于存储分类变量,分类变量是存储有条件数目的分类的;而连续变量则可以储存及对应一系列数目(可以无穷大)。简单例子:性别:男,女。永远是finite number of categories。
也即,每一个独立的分类代表了一个因子等级(factor level)。
R 会为每个独立的向量分配一个整数,创建一个value-label 对,value 对应向量中的元素,label 对应分配的数字。如果设定levels,将相当于手动添加了向量元素的label,不然则是R 替我们完成添加的工作,比如按照字母表顺序:
> expression <- c("low", "high", "medium", "high", "low", "medium", "high")
>
> expression <- factor(expression)
>
> expression
[1] low high medium high low medium high
Levels: high low medium
factor_sex_vector <- factor(sex_vector)
1)A nominal variable,表示没有内在顺序的变量类型。如动物的种类:猴子,兔子,老鼠。不同的动物之间不存在高低顺序的关联性。2)An ordinal variable,表示有一个排序关系。如描述程度关系的词:高,中,低。明显有一个内在关系。
# Animals
animals_vector <- c("Elephant", "Giraffe", "Donkey", "Horse")
factor_animals_vector <- factor(animals_vector)
factor_animals_vector
# Temperature
temperature_vector <- c("High", "Low", "High","Low", "Medium")
factor_temperature_vector <- factor(temperature_vector, order = TRUE, levels = c("Low", "Medium", "High"))
factor_temperature_vector
通过order,与level 调整 ordinal varibles 在factor 中的等级。
若没有通过定义factor直接设置levels 及顺序。可以之后语句添加
survey_vector <- c("M", "F", "F", "M", "M")
# 定义向量
factor_survey_vector <- factor(survey_vector)
# 定义因子
levels(factor_survey_vector) <- c("Female", "Male")
# 为因子定义level为Female,Male,因为按照默认顺序排列,字母表中F在M前
# 所以Female 会指代给F
# 这样的好处是在定义向量时不必完整的输入向量具体名称
# 直接在设定因子时定义即可。
factor_survey_vector
通过summary() 函数了解因子中不同类型变量的数值。
survey_vector <- c("M", "F", "F", "M", "M")
factor_survey_vector <- factor(survey_vector)
levels(factor_survey_vector) <- c("Female", "Male")
# 定义factor
summary(factor_survey_vector)
# 汇总并返回
'''
Female Male
2 3
'''
ps : 也可以给数字、字符串、矩阵使用summary()。数字
> summary(a)
Min. 1st Qu. Median Mean 3rd Qu. Max.
2 2 2 2 2 2
字符串
> summary(x2)
Length Class Mode
5 character character
矩阵
> summary(all_wars_matrix)
US non-US worldwide_vector
Min. :290.5 Min. :165.8 Min. :475.1
1st Qu.:299.9 1st Qu.:206.8 1st Qu.:506.7
Median :309.3 Median :247.9 Median :538.4
Mean :353.6 Mean :242.7 Mean :596.3
3rd Qu.:385.2 3rd Qu.:281.1 3rd Qu.:656.9
Max. :461.0 Max. :314.4 Max. :775.4
对于有条件关系的因子中的变量,ordinal variables,则会返回一个判断的布尔值。ps: 这类factor 在类别上也叫做ordered(至少Rstudio上是这样显示的) 如:
temperature_vector <- c("High", "Low", "High","Low", "Medium")
factor_temperature_vector <- factor(temperature_vector, order = TRUE, levels = c("Low", "Medium", "High"))
high <- factor_temperature_vector[1]
# 将本来向量顺序中的第一个值返还给high
low <- factor_temperature_vector[2]
high > low
返回
high > low
[1] TRUE
对于没有顺序关系,nominal variables,则会报错。
★Warning message: In Ops.factor(high, medium) : ‘>’ not meaningful for factors ”
性别不存在顺序。
# Build factor_survey_vector with clean levels
survey_vector <- c("M", "F", "F", "M", "M")
factor_survey_vector <- factor(survey_vector)
levels(factor_survey_vector) <- c("Female", "Male")
# Male
male <- factor_survey_vector[1]
# Female
female <- factor_survey_vector[2]
返回NA
目前为止学习到的内容:
★1)Vectors (one dimensional array): can hold numeric, character or logical values. The elements in a vector all have the same data type. 2)Matrices (two dimensional array): can hold numeric, character or logical values. The elements in a matrix all have the same data type. 3)Data frames (two-dimensional objects): can hold numeric, character or logical values. Within a column all elements have the same data type, but different columns can be of different data type. ”
一个R的列表包括了各种类型的变量,并将他们放置在同一个列表当中,这些变量可以是矩阵、向量、数据集,甚至是其他的列表。
其实都可以将list 理解为一个“super data type”,你可以在里面存储任何想要的信息。
给一个list ,外部为list 函数,每个元素可以为任何类型的数据。
列表的提取也可以按照类似数据框的方式提取。、 需要注意的是,列表用一个中括号提取内容,会返回一个列表,列表中包含提取的内容,只有用两个中括号,才会返回该内容本来的格式。
my_list <- list(my_vector, my_matrix, my_df)# 除此之外,我们还可以创建指定长度的空列表my_list <- vector("list", length = 5)
给list命名,和vector 之类命名一样一样。
names(my_list) <- c("vec", "mat", "df")
my_list
# 返回如下
'''
$vec
[1] 1 2 3 4 5 6 7 8 9 10
$mat
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
$df
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
'''
另外一种命名方式,直接在定义list的时候就对其进行命名
shining_list <- list(moviename = mov, actors = act, reviews = rev)
高效R 中提及,我们可以先分配指定长度的空list:
> means <- c(1, 50, 20)
> out <- vector("list", length(means))
>
> out
[[1]]
NULL
[[2]]
NULL
[[3]]
NULL
1)按照list中顺序获取。
shining_list[3]
# 第三个变量
2)检索list中变量名获取。
shining_list[["actors"]]
3)通过$
shining_list$actors
使用 unlist
可以解除list 中的所有元素,产生一个向量。
#删除
#删除一个
rm(l)
#删除多个
rm(df,m)
#删除全部
rm(list = ls())
删除全部可以帮助我们让脚本里运行的程序不受之前环境中的其他变量影响(放在首行)。Rstudio 中也有删除全部的选项。
眼见不一定为实,看返回结果才是真。
# 练习3-1
# 1.新建图示数据框,赋值给test1
gene <- paste0("gene", 1:15)
s1 <- rnorm(n=15,mean=0,sd=2)
s2 <- rnorm(n=15,mean=0,sd=2)
s3 <- rnorm(n=15,mean=0,sd=2)
df <- data.frame(gene,s1,s2,s3)
# (提示:后三列是用函数生成的随机数,
# 数值不必完全和我截图的相同)
# 2.读取excise.csv这个文件,赋值给test2。
test2 <- read.csv("excise.csv")
# 3.使用函数,查看test2的列名。
colnames(test2)
# 4.使用函数,查看test2的行数和列数。
dim(test2)
# 练习3-2
# 1. test = read.csv(“excise.csv”),提取test的第二行
test = read.csv("excise.csv")
test[2,]
# 2.提取第3行第4列
test[3,4]
# 3.求第二列数值的中位数
median(test[,2])
# 4.按照列名,同时提取s1,s3两列。
test[,c('s1','s3')]
# 5.修改后三列的列名为“sample1”,“sample2”,“sample3”
colnames(test)[2:4] <- paste0("sample",1:3)
# 6.提取sample3列数值大于0的所有行
test[test$sample3>0,]
#练习3-3
iris <- matrix(sample(1:20,15), nrow=3)
#1.统计iris最后一列有哪几个重复值,分别重复了多少次
table(iris[,ncol(iris)])
#2.提取iris的前4列,并转换为矩阵,赋值给test。
test <- as.matrix(iris[,1:4])
#3.将test的行名改为flower1,flower2...flower149,flower150。
rownames(test) <- paste0('flower',1:nrow(test))
#4.将test的第51到100行删除
test <- test[-(51:100),]
rm(test[51:100,])
#5.将iris和test组成一个列表,赋值给tl
t1 <- list(x1=iris, x2=test)
#6.提取tl的第二个元素
t1[[2]]
t1$x2
#7.修改tl第二个元素的名字为td
names(t1)[2] <- "td"