在日期/因子向量字段上使用 sapply - 包括递增值 [英] Using sapply on date/factor vector field - include incrementing value

查看:41
本文介绍了在日期/因子向量字段上使用 sapply - 包括递增值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含缺失值的日期字段(因子类转换为字符串),我想为每个缺失值填充序列号.到目前为止,这是我的代码...

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.

推荐答案

您的函数将 -9999 传递给每次 f 调用,然后将其加 1.这就是它每次返回 -9998 的原因.

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)

这篇关于在日期/因子向量字段上使用 sapply - 包括递增值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆