【问题标题】:For loop to fill NA with datesFor循环用日期填充NA
【发布时间】:2017-04-04 02:12:18
【问题描述】:

我有一个连续日期的 DF,后面有一些 NA,还值得一提的是 [1] 总是有一个日期。

我希望用连续的日期填写进行中的 NA。

我有:“2016-01-01”、“2016-01-02”、“2016-01-03”,不适用,不适用

DF 中的预期结果将是: “2016-01-01”、“2016-01-02”、“2016-01-03”、“2016-01-04”、“2016-01-05”

我尝试使用 for 循环,但我对此相当业余:

Date <-as.Date(c("2016-01-01", "2016-01-02", "2016-01-03", NA, NA))

DF <- as.data.frame(Date)

i <- which.max(is.na(DF$Date))
for (i in which.max(is.na(DF$Date)):max(length(DF$Date))){
  if(is.na(DF$Date)){
    DF$Date[i]= as.Date(max(DF$Date, na.rm=TRUE) + 1)
  }
}

它返回这个:

警告信息:

1: In if (is.na(DF$Date)) { :
  the condition has length > 1 and only the first element will be used
2: In if (is.na(DF$Date)) { :
  the condition has length > 1 and only the first element will be used

【问题讨论】:

    标签: date for-loop


    【解决方案1】:

    我自己发现了,if 语句不是一个单独的值,它列出了整个 DF,如果为真或假 NA。

    Date <-as.Date(c("2016-01-01", "2016-01-02", "2016-01-03", NA, NA))
    
    DF <- as.data.frame(Date)
    
    i <- which.max(is.na(DF$Date))
    for (i in which.max(is.na(DF$Date)):max(length(DF$Date))){
      if(which.max(is.na(DF$Date))){
        DF$Date[i]= as.Date(max(DF$Date, na.rm=TRUE) + 1)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-29
      • 2020-07-18
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多