简体   繁体   English

R 中的最后一次观察结转和最后一次观察结转

[英]Last observation carried forward and last observation carried backward in R

I have a dataset looking like this我有一个看起来像这样的数据集

df <- data.frame(ID=c(1,1,1,1,1,2,2,2,3,3), values=c(NA, NA, 12, 13, NA, 5, NA, NA, NA, 1))

I want an output like this, so that last observations are carried forward (by group) unless there are only NA values before one fillied-in value then I want last-observation carried backward:我想要一个像这样的 output ,以便最后的观察结果(按组)结转,除非在一个填充值之前只有 NA 值,然后我希望最后一个观察值向后进行:

df <- data.frame(ID=c(1,1,1,1,1,2,2,2,3,3), values=c(12, 12, 12, 13, 13, 5, 5, 5, 1, 1))

I have been working with dplyr and na.locf from the zoo package.我一直在使用动物园 package 的 dplyr 和 na.locf。 SO far my approach has been this:到目前为止,我的方法是这样的:

df%>%
group_by(PID%>%
mutate_all(funs(na.locf(., na.rm = FALSE)))

However, this only does last observation carried forward.然而,这只会将最后的观察结果发扬光大。 The specification "fromLast" in the na.locf function does last observation carried backward. na.locf function 中的规范“fromLast”确实向后进行了最后一次观察。

But how do I connect these two, so that both functions are used:但是我如何连接这两个,以便使用这两个功能:

  • na.LOCF if there are no NA values before the first filled-in value na.LOCF 如果在第一个填充值之前没有 NA 值
  • na.LOCF(fromLast) meaning last observation carried backward if there are NA values before the first value that is filled-in. na.LOCF(fromLast) 表示如果在填充的第一个值之前有 NA 值,则最后一个观察值向后移动。

Thank you so much in advance!非常感谢您!

This should work:这应该有效:

library(tidyverse)
df <- data.frame(ID=c(1,1,1,1,1,2,2,2,3,3), values=c(NA, NA, 12, 13, NA, 5, NA, NA, NA, 1))
df2 <- data.frame(ID=c(1,1,1,1,1,2,2,2,3,3), values=c(12, 12, 12, 13, 13, 5, 5, 5, 1, 1))

df <- df %>%
  group_by(ID) %>%
  fill(values, .direction = "downup") %>%
  fill(values, .direction = "updown")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM