当第一次观察为na时,使用na.locf向前传送最后一个值而忽略第一行 [英] Using na.locf to carry last value forward ignoring first rows when first observation is na

查看:85
本文介绍了当第一次观察为na时,使用na.locf向前传送最后一个值而忽略第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 na.locf 来结转首次观测值可能为零的数据帧的非缺失值。

I would like to make use of the na.locf to carry forward non-missing values for data frames where first observation may be zero.

dta <- data.frame(A = c(NA, NA, 1, 2, 4, 5, NA, NA, NA),
                  B = c(NA, 5, 4, 5, 8, 9, NA, NA, 100))
dta %>% mutate_all(.funs = funs(na.locf(.)))




mutate_impl(.data,点)中的错误: A 列的长度必须为9
(数字行)或一个而不是7

Error in mutate_impl(.data, dots) : Column A must be length 9 (the number of rows) or one, not 7



所需结果



Desired results

Vectorize(require)(package = c("dplyr", "zoo"),
                   character.only = TRUE)

dta <- data.frame(A = c(0, NA, 1, 2, 4, 5, NA, NA, NA),
                  B = c(0, 5, 4, 5, 8, 9, NA, NA, 100))
dta %>% mutate_all(.funs = funs(na.locf(.)))





潜在的解决方法可能是将第一组 NA 替换为零,并结转零,以后可以替换但我有兴趣将NA保留在原处,并探讨是否有一种简便的方法可以使 na.locf 忽略函数未接收非NA值的情况。开始更换。

Workaround

The potential workaround would could involve replacing first set of NAs with zeros and carrying zero forward that could be later replaced but I'm interested in leaving NAs where they are and exploring if there is a convenient way to make na.locf ignore situations where the function did not receive non-NA value to start replacing.

推荐答案

使用 na.rm = FALSE 参数指出它可以拿一个完整的数据框-您不必将其分别应用于每一列。

Use the na.rm = FALSE argument noting that it can take an entire data frame -- you don't have to separately apply it to each column.

na.locf(dta, na.rm = FALSE)

这给出了:

   A   B
1 NA  NA
2 NA   5
3  1   4
4  2   5
5  4   8
6  5   9
7  5   9
8  5   9
9  5 100

也有是na.locf0

dta %>% mutate_all(.funs = funs(na.locf0(.)))

帮助页面?na.locf ,其中记录了 na.rm 参数,还记录了 na。 locf0 。请注意,na.locf0当前确实必须按列单独应用,但始终会产生相同长度的输出。

See the help page ?na.locf which documents the na.rm argument and also documents na.locf0 . Note that na.locf0 currently does have to be applied individually by column but always produces output of the same length.

这篇关于当第一次观察为na时,使用na.locf向前传送最后一个值而忽略第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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