使用左连接在R中合并两个数据框。

huangapple go评论97阅读模式
英文:

Combining two data.frames in R with left-join

问题

I have the following data.frame called "A":

  1. structure(list(ID = c(111L, 222L, 333L, 444L, 555L, 666L)), row.names = c(NA, 6L), class = "data.frame")

along with the following data.frame called "B":

  1. structure(list(ID = c(111L, 222L, 444L, 555L, 777L, 888L), Created.At = c("2018-10-31 06:25:20", "2019-01-19 15:42:19", "2019-01-19 15:42:50", "2020-06-30 22:04:54", "2019-01-19 15:51:48", "2019-01-19 15:51:48")), row.names = c(NA, 6L), class = "data.frame")

I need to have the following output while combining data.frame A & B and then sorting by the ID having a left-join on data.frame A:

使用左连接在R中合并两个数据框。

英文:

I have the following data.frame called "A":

  1. structure(list(ID = c(111L, 222L, 333L,
  2. 444L, 555L, 666L)), row.names = c(NA, 6L), class = "data.frame")

along with the following data.frame called "B":

  1. structure(list(ID = c(111L, 222L, 444L,
  2. 555L, 777L, 888L), Created.At = c("2018-10-31 06:25:20",
  3. "2019-01-19 15:42:19", "2019-01-19 15:42:50", "2020-06-30 22:04:54",
  4. "2019-01-19 15:51:48", "2019-01-19 15:51:48")), row.names = c(NA,
  5. 6L), class = "data.frame")

I need to have the follwing output while combining data.frame A & B and then sorting by the ID having a left-join on data.frame A:

使用左连接在R中合并两个数据框。

答案1

得分: 2

  1. library(dplyr)
  2. C <- left_join(A, B, by="ID")
  3. C$Flg <- if_else(is.na(C$Created.At), "N", "Y")
  1. # ID Created.At Flg
  2. # 1 111 2018-10-31 06:25:20 Y
  3. # 2 222 2019-01-19 15:42:19 Y
  4. # 3 333 <NA> N
  5. # 4 444 2019-01-19 15:42:50 Y
  6. # 5 555 2020-06-30 22:04:54 Y
  7. # 6 666 <NA> N
英文:
  1. library(dplyr)
  2. C &lt;- left_join(A, B, by=&quot;ID&quot;)
  3. C$Flg &lt;- if_else(is.na(C$Created.At), &quot;N&quot;, &quot;Y&quot;)
  4. # ID Created.At Flg
  5. # 1 111 2018-10-31 06:25:20 Y
  6. # 2 222 2019-01-19 15:42:19 Y
  7. # 3 333 &lt;NA&gt; N
  8. # 4 444 2019-01-19 15:42:50 Y
  9. # 5 555 2020-06-30 22:04:54 Y
  10. # 6 666 &lt;NA&gt; N

huangapple
  • 本文由 发表于 2023年5月24日 17:26:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76322011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定