在向量内传播数据 [英] propagating data within a vector

查看:33
本文介绍了在向量内传播数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 R 并且很好奇...我需要一个函数来执行此操作:

I'm learning R and I'm curious... I need a function that does this:

> fillInTheBlanks(c(1, NA, NA, 2, 3, NA, 4))
[1] 1 1 1 2 3 3 4
> fillInTheBlanks(c(1, 2, 3, 4))
[1] 1 2 3 4

我制作了这个...但我怀疑有更多的 R 方法可以做到这一点.

and I produced this one... but I suspect there's a more R way to do this.

fillInTheBlanks <- function(v) {
  ## replace each NA with the latest preceding available value

  orig <- v
  result <- v
  for(i in 1:length(v)) {
    value <- v[i]
    if (!is.na(value))
      result[i:length(v)] <- value
  }
  return(result)
}

推荐答案

zoo有一个函数na.locf():

R> library("zoo")
R> na.locf(c(1, 2, 3, 4))
[1] 1 2 3 4
R> na.locf(c(1, NA, NA, 2, 3, NA, 4))
[1] 1 1 1 2 3 3 4

na.locf:最后一次观察结转;用之前的最新非NA"替换每个NA"的通用函数.

na.locf: Last Observation Carried Forward; Generic function for replacing each ‘NA’ with the most recent non-‘NA’ prior to it.

查看函数na.locf.default的源代码,它不需要for-loop.

See the source code of the function na.locf.default, it doesn't need a for-loop.

这篇关于在向量内传播数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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