R-遍历每一行并填充上一行的值 [英] R - Loop through each row and fill with value from previous row

查看:630
本文介绍了R-遍历每一行并填充上一行的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试特定列中的值是否包含NA值,如果是,则用上一行中的值填充该NA空间.我仍在尝试摆脱apply函数家族的束缚.

I'd like to test whether a value from a particular column contains an NA value, and if so, fill that NA space with the value from the previous row. I'm still trying to get the hang of the apply family of functions.

例如我要转这个:

      Date   Balance
2012-01-01      1000
2012-01-02        NA
2012-01-03        NA
2012-01-04      1200
2012-01-05      1215
2012-01-06        NA

进入:

      Date   Balance
2012-01-01      1000
2012-01-02      1000
2012-01-03      1000
2012-01-04      1200
2012-01-05      1215
2012-01-06      1215

推荐答案

这是Zoo包中用于na.locf功能的任务.参见?na.locf

This is a task for na.locf function from zoo package. See ?na.locf

考虑DF是您的data.frame,然后:

Consider DF is your data.frame, then:

DF <- read.table(text="      Date   Balance
2012-01-01      1000
2012-01-02        NA
2012-01-03        NA
2012-01-04      1200
2012-01-05      1215
2012-01-06        NA", header=TRUE)

library(zoo)
na.locf(DF)
        Date Balance
1 2012-01-01    1000
2 2012-01-02    1000
3 2012-01-03    1000
4 2012-01-04    1200
5 2012-01-05    1215
6 2012-01-06    1215

这篇关于R-遍历每一行并填充上一行的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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