更新可能没有解释清楚。这里用原始数据解释一下:
创建左连接
left <- left_join(expression, clinical2, by = c("patient" = "patientID"))
dim(expression)
[1] 570 8
dim(left)
[1] 570 10
创建右连接
right <- right_join(expression, clinical2,
by = c("patient" = "patientID"))
dim(expression)
[1] 570 8
dim(right)
[1] 573 10
你想知道为什么 dim(right) 是 573!
一步一步解释:
-
right_join() 的定义:包括y 中的所有行(y 在这里是clinical2)。
- 这样做:
clinical2 (y) 中有 3 行不在 expression (x) 中
请看这里:
哪个患者出现在clinical2 但不在expression
anti_join(clinical2, expression, by=c("patientID"="patient"))
patientID gender years_at_diagnosis
<chr> <chr> <dbl>
1 TCGA-55-7284 male 74.2
2 TCGA-55-7913 female 61.2
3 TCGA-67-4679 male 69.0
再次:
right_join(expression, clinical2, by = c("patient" = "patientID"))
我们从expression(x) (dim = 570 8) 开始并加入clinical2 (y) (dim = 516 3)
那么现在会发生什么:
-
expression (x) 中的所有 570 都与 clinial2 (y) 中的所有匹配 (dim = 516 3) EXCEPT 这 3 个患者 ID
在clinical2TCGA-55-7284, TCGA-55-7913, TCGA-67-4679
-
right_join 现在从 expression 中取出所有 570,并从 clinical2 添加不匹配的 3 个 patientID 导致 573 10 的暗淡
- 相比之下
left_join:
left_join():包括 x 中的所有行 (=expression),所以如果我们这样做
anti_join(expression, clinical2, by=c("patient"="patientID"))
We get:
# ... with 8 variables: sampleID <fct>, patient <chr>, type <chr>, A1BG <dbl>, A1CF <dbl>,
# A2BP1 <dbl>, A2LD1 <dbl>, A2ML1 <dbl>````
这意味着所有行都包含在表达式中。所以这里不会添加额外的行:
第一个答案:
加入两件事很重要:
- 您从哪一侧开始加入,例如哪个表在第一位
- 给定的表格位置,例如df1, df2 你应用哪种连接方式
看这个例子:
library(dplyr)
library(tibble)
# add ID
iris1<- iris %>%
tibble::rowid_to_column("ID")
# add ID
mtcars1 <- mtcars %>%
tibble::rowid_to_column("ID")
dim(iris1)
# [1] 150 6
dim(mtcars1)
# [1] 32 12
# 1. iris1 is first and we start from left e.g. iris1
a <- left_join(iris1, mtcars1, by="ID")
dim(a)
# [1] 150 17
# 2. iris1 is still first, but we join from right e.g. mtcars1
b <- right_join(iris1, mtcars1, by="ID")
dim(b)
# [1] 32 17
# 3. mtcars1 is first and we join from left e.g mtcars1
a1 <- left_join(mtcars1, iris1, by="ID")
dim(a1)
# [1] 32 17
-> b = a1 e.g. right_join(iris1, mtcars1, by="ID") = left_join(mtcars1, iris1, by="ID")
https://www.rdocumentation.org/packages/dplyr/versions/0.7.8/topics/join