生信学习基础_R语言06_Matching reordering匹配与排序

原文地址:https://hbctraining.github.io/Intro-to-R/lessons/06_matching_reordering.html

大神的中文整理版:https://www.jianshu.com/p/91f3aaa73b3f

本文是我拷贝的原文,加了自己的笔记和练习题答案。

Learning Objectives

  • Implement matching and re-ordering data within data structures.

Matching data

Often when working with genomic data, we have a data file that corresponds with our metadata file. The data file contains measurements from the biological assay for each individual sample. In this case, the biological assay is gene expression and data was generated using RNA-Seq.

Let’s read in our expression data (RPKM matrix) that we downloaded previously:

rpkm_data <- read.csv("data/counts.rpkm.csv")

Take a look at the first few lines of the data matrix to see what’s in there.

head(rpkm_data)

It looks as if the sample names (header) in our data matrix are similar to the row names of our metadata file, but it’s hard to tell since they are not in the same order. We can do a quick check of the number of columns in the count data and the rows in the metadata and at least see if the numbers match up.

ncol(rpkm_data)
nrow(metadata)

What we want to know is, do we have data for every sample that we have metadata?

The %in% operator

Although lacking in documentation this operator is well-used and convenient once you get the hang of it. The operator is used with the following syntax:

vector1_of_values %in% vector2_of_values

It will take a vector as input to the left and will evaluate each element to see if there is a match in the vector that follows on the right of the operator. The two vectors do not have to be the same size. This operation will return a vector of the same length as vector1 containing logical values to indicate whether or not there was a match. Take a look at the example below:

A <- c(1,3,5,7,9,11)   # odd numbers
B <- c(2,4,6,8,10,12)  # even numbers

# test to see if each of the elements of A is in B  
A %in% B

## [1] FALSE FALSE FALSE FALSE FALSE FALSE

Since vector A contains only odd numbers and vector B contains only even numbers, there is no overlap and so the vector returned contains a FALSE for each element. Let’s change a couple of numbers inside vector B to match vector A:

A <- c(1,3,5,7,9,11)   # odd numbers
B <- c(2,4,6,8,1,5)  # add some odd numbers in 

# test to see if each of the elements of A is in B
A %in% B

## [1]  TRUE FALSE  TRUE FALSE FALSE FALSE

The logical vector returned denotes which elements in A are also in B and which are not.

We saw previously that we could use the output from a logical expression to subset data by returning only the values corresponding to TRUE. Therefore, we can use the output logical vector to subset our data, and return only those elements in A, which are also in B by returning only the TRUE values:

matching1
intersection <- A %in% B
intersection

matching2
A[intersection]

matching3

In these previous examples, the vectors were small and so it’s easy to count by eye; but when we work with large datasets this is not practical. A quick way to assess whether or not we had any matches would be to use the any function to see if any of the values contained in vector A are also in vector B:

any(A %in% B)

The all function is also useful. Given a logical vector, it will tell you whether all values returned are TRUE. If there is at least one FALSE value, the all function will return a FALSE and you know that all of A are not contained in B.

all(A %in% B)


Exercise 1

  1. Using the A and B vectors created above, evaluate each element in B to see if there is a match in A
  1. Subset the B vector to only return those values that are also in A.
B %in% A
B[B %in% A]

Suppose we had two vectors that had the same values but just not in the same order. We could also use all to test for that. Rather than using the %in% operator we would use == and compare each element to the same position in the other vector. Unlike the %in% operator, for this to work you must have two vectors that are of equal length.

A <- c(10,20,30,40,50)
B <- c(50,40,30,20,10)  # same numbers but backwards 

# test to see if each element of A is in B
A %in% B

# test to see if each element of A is in the same position in B
A == B

# use all() to check if they are a perfect match
all(A == B)

Let’s try this on our data and see whether we have metadata information for all samples in our expression data. We’ll start by creating two vectors; one with the rownames of the metadata and colnames of the RPKM data. These are base functions in R which allow you to extract the row and column names as a vector:

x <- rownames(metadata)
y <- colnames(rpkm_data)

Now check to see that all of x are in y:

all(x %in% y)

Note that we can use nested functions in place of x and y:

all(rownames(metadata) %in% colnames(rpkm_data))

We know that all samples are present, but are they in the same order:

all(rownames(metadata) == colnames(rpkm_data))

Looks like all of the samples are there, but will need to be reordered. To reorder our genomic samples, we need to first learn different ways to reorder data. Therefore, we will step away from our genomic data briefly to learn about reordering, then return to it at the end of this lesson.


Exercise 2

We have a list of IDs for marker genes of particular interest. We want to extract count information associated with each of these genes, without having to scroll through our matrix of count data. We can do this using the %in% operator to extract the information for those genes from rpkm_data.

  1. Create a vector for your important gene IDs, and use the %in%operator to determine whether these genes are contained in the row names of our rpkm_data dataset.

     important_genes <- c("ENSMUSG00000083700", "ENSMUSG00000080990", "ENSMUSG00000065619", "ENSMUSG00000047945", "ENSMUSG00000081010",     "ENSMUSG00000030970")
    
    

important_genes %in% rownames(rpkm_data)
```

  1. Extract the rows containing the important genes from your rpkm_data dataset using the %in%operator.
rpkm_data[rownames(rpkm_data)[rownames(rpkm_data) %in% important_genes],]
  1. Extra Credit: Using the important_genes vector, extract the rows containing the important genes from your rpkm_data dataset without using the %in% operator.
rpkm_data[important_genes,]

Reordering data using indices

Indexing [ ] can be used to extract values from a dataset as we saw earlier, but we can also use it to rearrange our data values.

teaching_team <- c("Mary", "Meeta", "Radhika")

reordering

Remember that we can return values in a vector by specifying it’s position or index:

teaching_team[c(2, 3)] # Extracting values from a vector
teaching_team

We can also extract the values and reorder them:

teaching_team[c(3, 2)] # Extracting values and reordering them

Similarly, we can extract all of the values and reorder them:

teaching_team[c(3, 1, 2)]

If we want to save our results, we need to assign to a variable:

reorder_teach <- teaching_team[c(3, 1, 2)] # Saving the results to a variable

The match function

Now that we know how to reorder using indices, we can use the match() function to match the values in two vectors. We’ll be using it to evaluate which samples are present in both our counts and metadata dataframes, and then to re-order the columns in the counts matrix to match the row names in the metadata matrix.

match() takes at least 2 arguments:

  1. a vector of values in the order you want
  2. a vector of values to be reordered

The function returns the position of the matches (indices) with respect to the second vector, which can be used to re-order it so that it matches the order in the first vector. Let’s create vectors firstand second to demonstrate how it works:

first <- c("A","B","C","D","E")
second <- c("B","D","E","A","C")  # same letters but different order

matching4

How would you reorder second vector to match first using indices?

If we had large datasets, it would be difficult to reorder them by searching for the indices of the matching elements. This is where the match function comes in really handy:

match(first,second)
[1] 4 1 5 2 3

The function should return a vector of size length(first). Each number that is returned represents the index of the second vector where the matching value was observed.

Now, we can just use the indices to reorder the elements of the second vector to be in the same positions as the matching elements in the first vector:

reorder_idx <- match(first,second) # Saving indices for how to reorder `second` to match `first`

second[reorder_idx]  # Reordering the second vector to match the order of the first vector
second_reordered <- second[reorder_idx]  # Reordering and saving the output to a variable

matching7

Now that we know how match() works, let’s change vector second so that only a subset are retained:

first <- c("A","B","C","D","E")
second <- c("D","B","A")  # remove values

matching5

And try to match() again:

match(first,second)

[1]  3  2 NA  1 NA

NOTE: For values that don’t match by default return an NA value. You can specify what values you would have it assigned using nomatch argument. Also, if there is more than one matching value found only the first is reported.

Reordering genomic data using match() function

Using the match function, we now would like to match the row names of our metadata to the column names of our expression data*, so these will be the arguments for match. Using these two arguments we will retrieve a vector of match indices. The resulting vector represents the re-ordering of the column names in our data matrix to be identical to the rows in metadata:

rownames(metadata)

colnames(rpkm_data)

genomic_idx <- match(rownames(metadata), colnames(rpkm_data))
genomic_idx

Now we can create a new data matrix in which columns are re-ordered based on the match indices:

rpkm_ordered  <- rpkm_data[,genomic_idx]

Check and see what happened by using head. You can also verify that column names of this new data matrix matches the metadata row names by using the all function:

head(rpkm_ordered)
all(rownames(metadata) == colnames(rpkm_ordered))

Now that our samples are ordered the same in our metadata and counts data, if these were raw counts we could proceed to perform differential expression analysis with this dataset.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,200评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,526评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,321评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,601评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,446评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,345评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,753评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,405评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,712评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,743评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,529评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,369评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,770评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,026评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,301评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,732评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,927评论 2 336

推荐阅读更多精彩内容