在数据框中结转的上次观察结果? [英] Last Observation Carried Forward In a data frame?

查看:21
本文介绍了在数据框中结转的上次观察结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望实施最后一次观察结转";对于我正在处理的数据集,其末尾有缺失值.

I wish to implement a "Last Observation Carried Forward" for a data set I am working on which has missing values at the end of it.

这是一个简单的代码来做到这一点(后面的问题):

Here is a simple code to do it (question after it):

LOCF <- function(x)
{
    # Last Observation Carried Forward (for a left to right series)
    LOCF <- max(which(!is.na(x))) # the location of the Last Observation to Carry Forward
    x[LOCF:length(x)] <- x[LOCF]
    return(x)
}


# example:
LOCF(c(1,2,3,4,NA,NA))
LOCF(c(1,NA,3,4,NA,NA))

现在这适用于简单的向量.但是,如果我在哪里尝试在数据框上使用它:

Now this works great for simple vectors. But if I where to try and use it on a data frame:

a <- data.frame(rep("a",4), 1:4,1:4, c(1,NA,NA,NA))
a
t(apply(a, 1, LOCF)) # will make a mess

它将把我的数据框变成一个字符矩阵.

It will turn my data frame into a character matrix.

你能想出一种在data.frame上做LOCF而不用把它变成矩阵的方法吗?(我可以使用循环等来纠正混乱,但希望有一个更优雅的解决方案)

Can you think of a way to do LOCF on a data.frame, without turning it into a matrix? (I could use loops and such to correct the mess, but would love for a more elegant solution)

推荐答案

这个已经存在:

library(zoo)
na.locf(data.frame(rep("a",4), 1:4,1:4, c(1,NA,NA,NA)))

这篇关于在数据框中结转的上次观察结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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