gpt4 book ai didi

r - 按 id 和 date 合并两个数据框

转载 作者:行者123 更新时间:2023-12-04 09:15:52 25 4
gpt4 key购买 nike

我有两个数据框。
A:

id  date
1 2010-05-08
2 2012-08-08
3 2013-06-23
乙:
id  date1
1 2010-05-09
2 2012-08-08
我需要通过 id 以及表 2 中的日期 = 表 1 中的日期 +1 天来合并两个数据框。进一步标记合并为 TRUE 的行。
最终输出是
A:
id  date           date1      flag
1 2010-05-08 2010-05-09 1
2 2012-08-08 NA NA
3 2013-06-23 NA NA
生成数据的代码-
A <- data.frame(customer = c(1,2,3),
application_date = c("2010-05-08", "2012-08-08", "2013-06-23"))
B <- data.frame(customer = c(1,2),
application_date = c("2010-05-09", "2012-08-08"))

最佳答案

这个怎么样?
数据 :

A <- data.frame(customer = c(1,2,3),
application_date = c("2010-05-08", "2012-08-08", "2013-06-23"))
B <- data.frame(customer = c(1,2),
application_date = c("2010-05-09", "2012-08-08"))
DPLYR :
library(dplyr)

data <- left_join(A, B, by = "customer")
data %>%
mutate(logic = if_else(as.Date(data$application_date.x) + 1 == as.Date(data$application_date.y), 1, 0)) %>%
rename("id" = "customer",
"date" = "application_date.x",
"date1" = "application_date.y",
"flag" = "logic")
输出 :
 id       date          date1         flag
1 2010-05-08 2010-05-09 1
2 2012-08-08 2012-08-08 0
3 2013-06-23 <NA> NA
数据表 :
library(data.table)

data_2 <- merge.data.table(A, B, by = "customer", all.x=TRUE)
data_2[, logic:= (ifelse(as.Date(data$application_date.x) + 1 == as.Date(data$application_date.y), 1, 0))]
setnames(data_2, old = c("customer", "application_date.x", "application_date.y", "logic"),
new = c("id", "date", "date1", "flag"))
输出 :
 id       date          date1         flag
1 2010-05-08 2010-05-09 1
2 2012-08-08 2012-08-08 0
3 2013-06-23 <NA> NA

关于r - 按 id 和 date 合并两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63220443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com