R中的嵌套循环

R中的嵌套循环,r,R,我想比较两个文件中的电子邮件ID,如果它们匹配,然后找出日期之间的差异。可能会出现多对多的情况(电子邮件id可能会在两个文件中重复) 我尝试使用嵌套循环和IF条件 library(openair) pp<-read.csv(file.choose(),header=T) pe<-read.csv(file.choose(),header=T) for(i in 1 : nrow(pp)) { for(j in 1 : nrow(pe)) { if(is

我想比较两个文件中的电子邮件ID,如果它们匹配,然后找出日期之间的差异。可能会出现多对多的情况(电子邮件id可能会在两个文件中重复)

我尝试使用嵌套循环和IF条件

 library(openair)
 pp<-read.csv(file.choose(),header=T)
 pe<-read.csv(file.choose(),header=T)
 for(i in 1 : nrow(pp))
 {
   for(j in 1 : nrow(pe))
   {
     if(is.na(pp$RIDER_EMAIL) == is.na(pe$RIDER_EMAIL))
     {
       x[i][j] = pp$Created.Date2-pe$Expired.Date
     }
   }
 }
库(露天)

pp注意下面代码中的以下内容。我不知道它是否真的适用于您的数据,因为您没有提供任何示例数据集(请下次再提供)

  • 我倾向于将数据保存到列表中,因为它们更通用
  • pp$RIDER\u电子邮件[i]!=pe$RIDER_电子邮件[j]
    等同于询问这两个元素是否不同
  • 在循环中声明时,不要忘记使用
    i
    j
    (或任何变量)
  • 库(露天)
    
    pp将来,创建一个可复制的示例将帮助您更快地获得答案。在这里,我为你创造了这个。在这个答案中,我假设您知道如何处理日期,我只是展示了对两个表进行多对多连接并计算两个字段之间差异的解决方案

    首先创建一些假数据。注意,对于日期字段,我只使用了一个整数

    # Create fake data
    library(tibble)
    mail1 <- tribble(
      ~emailID, ~date,
      "a", 12,
      "a", 13,
      "c", 12,
      "d", 12,
    )
    
    mail2 <- tribble(
      ~emailID, ~date,
      "a", 1,
      "a", 2,
      "c", 1,
      "d", 1,
    )
    
    #创建假数据
    图书馆(tibble)
    
    mail1没有示例数据很难提供帮助,但是您的代码有很多问题。特别是,
    if()
    比较没有意义,
    x
    是未定义的。但是嵌套循环在这里不是一个好的解决方案。最好通过电子邮件ID连接两个数据帧,然后在新列中计算日期差。我会看看
    dplyr
    连接和
    mutate()
        library(openair)
         pp<-read.csv(file.choose(),header=T)
         pe<-read.csv(file.choose(),header=T)
    
        x<-list()
        y<-list()
         for(i in 1 : nrow(pp))
         {
           for(j in 1 : nrow(pe))
           {
             if(pp$RIDER_EMAIL[i] != pe$RIDER_EMAIL[j])
             {
               x[[j]] = pp$Created.Date2[i]-pe$Expired.Date[j]
             }
           }
          y[[i]]<-x
         }
    
    # Create fake data
    library(tibble)
    mail1 <- tribble(
      ~emailID, ~date,
      "a", 12,
      "a", 13,
      "c", 12,
      "d", 12,
    )
    
    mail2 <- tribble(
      ~emailID, ~date,
      "a", 1,
      "a", 2,
      "c", 1,
      "d", 1,
    )
    
    library(dplyr)
    
    # rename the date column in the second dataset, this helps with the merge. 
    mail2 <- mail2 %>% 
      rename(date2 = date)
    
    # Merge, note row inflation through many to many match, and calculate the difference.
    compare <- 
      full_join(mail1, mail2, by = "emailID") %>% 
      mutate(difference = date - date2)