2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

base::merge()とdplyr::*_join()

Posted at

対応表 おおむねこんな感じ?

merge dplyr
merge (x, y) inner_join(x, y)
merge (x, y, all.x = TRUE) left_join(x, y)
merge (x, y, all.y = TRUE) right_join(x,y)
merge (x, y, all = TRUE) full_join(x,y)

実行例

> (x <- data.frame (a = 1:3, b = c ("A", "B", "C"), x1 = 11:13))
  a b x1
1 1 A 11
2 2 B 12
3 3 C 13
> (y <- data.frame (a = 2:4, b = c ("B", "C", "D"), y1 = 21:23))
  a b y1
1 2 B 21
2 3 C 22
3 4 D 23
> # デフォルトでは重複する要素のある行のみ出力
> merge (x, y)
  a b x1 y1
1 2 B 12 21
2 3 C 13 22
> dplyr::inner_join(x, y, by = c("a", "b"))#に相当
  a b x1 y1
1 2 B 12 21
2 3 C 13 22
Warning message:
In inner_join_impl(x, y, by$x, by$y) :
  joining factors with different levels, coercing to character vector

ただしb列は、それぞれの水準が異なるので文字列化されている

「x」列を基準に結合

> merge (x, y, all.x = TRUE)
  a b x1 y1
1 1 A 11 NA
2 2 B 12 21
3 3 C 13 22
> dplyr::left_join(x, y, by = c("a", "b"))#に相当
  a b x1 y1
1 1 A 11 NA
2 2 B 12 21
3 3 C 13 22
Warning message:
In left_join_impl(x, y, by$x, by$y) :
  joining factors with different levels, coercing to character vector

「y」列を基準に結合

> merge (x, y, all.y = TRUE)
  a b x1 y1
1 2 B 12 21
2 3 C 13 22
3 4 D NA 23
> dplyr::right_join(x, y, by = c("a", "b"))#に相当
  a b x1 y1
1 2 B 12 21
2 3 C 13 22
3 4 D NA 23
Warning message:
In right_join_impl(x, y, by$x, by$y) :
  joining factors with different levels, coercing to character vector

両方の列要素を網羅した結合

> merge (x, y, all = TRUE)
  a b x1 y1
1 1 A 11 NA
2 2 B 12 21
3 3 C 13 22
4 4 D NA 23
> dplyr::full_join(x, y, by = c("a", "b"))#に相当
  a b x1 y1
1 1 A 11 NA
2 2 B 12 21
3 3 C 13 22
4 4 D NA 23
Warning message:
In outer_join_impl(x, y, by$x, by$y) :
  joining factors with different levels, coercing to character vector
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?