【问题标题】:Filter one dataframe based on two conditions from another dataframe根据来自另一个数据帧的两个条件过滤一个数据帧
【发布时间】:2019-07-16 12:54:02
【问题描述】:

我有两个数据框,第一个有 3 万行,第二个有 571 行。

我需要用第二个的 2 个条件过滤第一个。

条件 A:(fctr) DF1$Col1 == [i]DF2$Col1

标准 B:(日期)DF1$Col2

df1 = data.frame(col1 = c("a","a","a","b","b","b","b","c","c"), col2 = c("10/02", "15/02", "14/03", "05/03", "07/03", "15/03", "20/03", "12/03", "15/03"))
df2 = data.frame(col1 = c("a","b","c"), col2 = c("15/02", "15/03", "15/03"))

我需要这样的东西:

dataframe3 = filter(df1, col1 == [i]df2$col1 & col2 <= [i]df2$col2)

#or

for(i in df2$col1){
  a=filter(df1, col1 ==i)
  for(e in df2$col2){ #here is the problem, i don't want loop in all dates
    b[]=filter(a, col2 <=e)}

【问题讨论】:

  • 什么是col1col2函数?请格式化您的示例。它给出了错误。另外,请显示预期的输出
  • 您是说要根据第二个数据帧的第 i 行保留第一个数据帧的行吗?
  • @ArturoSbr 没有。我想创建一个新的数据框,在其中使用 dataframe2 中的条件过滤 dataframe1
  • @akrun col1 和 col2 是数据框中的向量。我做了一些修改,谢谢。

标签: r dplyr


【解决方案1】:

如果我理解正确,这应该可以满足您的要求:

# Add year to make the columns readable as dates
df1$col2 <- as.Date(paste0(df1$col2, "/2019"), format = "%d/%m/%Y")
df2$col2 <- as.Date(paste0(df2$col2, "/2019"), format = "%d/%m/%Y")

# Create df3 such that col1 mathces both dataframes
df3 <- merge(df1, df2, by = "col1", all.y = TRUE)

# Keep rows where df1$col2 <= df2$col2
df3 <- df3[df3$col2.x <= df3$col2.y, c("col1", "col2.x")]

# Rename columns
setnames(df3, "col2.x", "col2")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    相关资源
    最近更新 更多