【问题标题】:I want to created another column in the first dataframe based on values of second column prior to or on the date of first dataframe for each group我想根据每个组的第一个数据框的日期之前或之日的第二列的值在第一个数据框中创建另一列
【发布时间】:2025-12-13 09:20:05
【问题描述】:

我有两个数据框,一个具有唯一 ID,另一个具有多个 ID。如果在第一个数据帧日期或之前的第二个数据帧中的值的值为 1,并且如果第二个数据帧中缺少 id 我想分配 NA,我想在第一个数据帧中创建另一列。在 R 中最有效的方法是什么?

# first dataframe with each unique id 
set.seed(123)
df <- data.frame(id = c(1:7),
                 date = seq(as.Date("2020/12/26"),
                            as.Date("2021/1/1"), by = "day"))

#s second dataframe with repeated id 
df1 <- data.frame(id = rep(1:5, each = 5),
                  date = sample(seq(as.Date('2020/12/20'), 
                                    as.Date('2021/1/15'), by="day"), 25),
                  assign = sample(c(0,1), replace=TRUE, size=25))

df1 <- arrange(df1,id, date)

# the output that I want 
df$response <- c(1,0,0,1,0,NA,NA)

【问题讨论】:

  • 是的,我更新了回复

标签: r dplyr data.table


【解决方案1】:

也许我们可以使用连接

library(data.table)
df2 <- setDT(df1)[as.logical(assign)]
setDT(df)[df2, response := assign, on = .(id, date), roll = -Inf]
df[is.na(response) & id %in% df2$id, response := 0]

-输出

df
#   id       date response
#1:  1 2020-12-26        1
#2:  2 2020-12-27        0
#3:  3 2020-12-28        0
#4:  4 2020-12-29        1
#5:  5 2020-12-30        0
#6:  6 2020-12-31       NA
#7:  7 2021-01-01       NA

【讨论】:

  • 非常感谢!是否可以使用 dplyr 给我与上述代码等效的代码? @akrun
  • 似乎该解决方案不适用于我的实际数据帧,我认为这可能是因为在我的其他数据帧中,有时 ID 始终为 0。您认为您的解决方案即使在id 在第二个数据框中只有 0 个值。
最近更新 更多