【问题标题】:R for loop generating NA's after 1000 iterationsR for 循环在 1000 次迭代后生成 NA
【发布时间】:2021-03-14 19:00:29
【问题描述】:

我有一个简单的 for 循环,用于从我的数据帧中删除任何行,这些行涉及共享相似字符串的两个变量,当我运行循环时,它会迭代 1000 次,然后开始生成 NA,这会破坏我的循环。

expiration quote_datetime
2021-02-26 2021-02-26 10:00:00
2021-02-26 2021-02-27 10:00:00
for(row in 1:nrow(df)){
  if(grepl(df$expiration[row], df$quote_datetime[row],fixed=TRUE) == TRUE){
    df = df[-row,]
  }
}

我收到错误消息

if (grepl(df$expiration[row], df$quote_datetime[row], 中的错误: 需要 TRUE/FALSE 的缺失值

每次我运行它时,它都会消除更多的行,直到它用完任何其他要消除的行,然后它运行而没有错误。感谢帮助。

【问题讨论】:

    标签: r dataframe for-loop


    【解决方案1】:

    出现问题是因为原始数据 'df' 获得子集 if 条件为 TRUE,即对于每个 if TRUE 情况,它将少一行。如果我们复制数据就可以解决问题

    df2 <- df
    for(row in 1:nrow(df)){
       if(grepl(df$expiration[row], df$quote_datetime[row],fixed=TRUE)){
         df2 <- df2[-row,]
        }
       }
    

    另外,grepl 仅针对 'x' 而不是针对 pattern 进行矢量化所以,如果我们需要进行矢量化,可能需要将 pastepattern 一起进行

    df <- df[!grepl(paste(df$expiration, collapse="|"), 
                  df$quote_datetime, fixed = TRUE), ]
    

    或者使用对“x”和“模式”进行矢量化的函数,即str_detect

    library(dplyr)
    library(stringr)
    df %>%
       filter(!str_detect(quote_datetime, fixed(expiration))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-05
      • 1970-01-01
      • 1970-01-01
      • 2015-11-11
      • 1970-01-01
      • 2021-12-20
      • 2010-12-28
      相关资源
      最近更新 更多