如何在不使用其他程序包的情况下在R中na.locf [英] How to na.locf in R without using additional packages

查看:317
本文介绍了如何在不使用其他程序包的情况下在R中na.locf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个向量(例如)(c(2,NA,5,NA,NA,1,NA)),问题是最后观察结转"产生向量c(2,2,5,5,5,1,1).

Given a vector such as (say) c(2,NA,5,NA,NA,1,NA) the problem is to "last observation carry forward" resulting in vector c(2,2,5,5,5,1,1).

回答无需加载程序包.有没有一种方法可以仅使用基本R来简单快速地做到这一点? (向量可能很长,可能包含许多连续的NA.)

As answered here, na.locf from the zoo package can do this. However, given the simplicity of the problem, and the fact that this is to be performed many times from a "blank" R environment, I would like to do this without loading packages. Is there a way to do it simply and quickly using just basic R? (The vector may be long and may contain many consecutive NAs.)

推荐答案

zoo::na.locf.default

fillInTheBlanks <- function(S) {
  L <- !is.na(S)
  c(S[L][1], S[L])[cumsum(L)+1]
}

另请参见此处.

这篇关于如何在不使用其他程序包的情况下在R中na.locf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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