Using sapply on date/factor vector field - include incrementing value

╄→尐↘猪︶ㄣ 提交于 2020-01-15 05:27:24

问题


I have a date field (factor class converted to string) with missing values that I would like to fill with sequencing numbers for every missing value. Here is my code so far...

f<- function(x, counter){
  if(x == ""){
      counter = counter + 1; return (toString(counter))
  } else{
      return (toString(x))
  }
}
sapply(x$DateTime_, f, -9999)

The counter does not increment and returns a vector like:

[1] "-9998"    "-9998"    "-9998"    "-9998"    "-9998"    "1/1/1998"

Any help to get the counter to increment would be appreciated.


回答1:


Your function passes -9999 to each call of f and then increments it by 1. This is why it's returning -9998 each time.

You probably want to maintain the counter variable in the parent environment and update it with the <<- operator. Something like this would do the trick for your example:

f = function(x) {
  if (x == "") {
    counter <<- counter + 1
    return(toString(counter))
  } else {
    return(toString(x))
  }
}
counter <- -9999
sapply(c("", "", "", "", "", "1/1/1998"), f)



回答2:


Here is another way to accomplish the same goal. It takes advantage of logical indexing and the inherently vectorized comparison and replacement operators:

dates <- c("", "", "", "", "", "1/1/1998", "")
blanks <- dates == ""

dates[blanks] <- seq(from=-9999, by=1, length.out=sum(blanks))

dates
# [1] "-9999"    "-9998"    "-9997"    "-9996"    "-9995"    "1/1/1998" "-9994"   


来源:https://stackoverflow.com/questions/20531514/using-sapply-on-date-factor-vector-field-include-incrementing-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!