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

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

Combining two data.frames in R with left-join

问题

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

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":

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":

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":

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 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

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

#    ID          Created.At Flg
# 1 111 2018-10-31 06:25:20   Y
# 2 222 2019-01-19 15:42:19   Y
# 3 333                &lt;NA&gt;   N
# 4 444 2019-01-19 15:42:50   Y
# 5 555 2020-06-30 22:04:54   Y
# 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:

确定