最后观察结束在数据框架? [英] Last Observation Carried Forward In a data frame?
本文介绍了最后观察结束在数据框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望对我正在工作的数据集执行最后观察结束,在其末尾缺少值。
这是一个简单的代码来做(问题之后):
LOCF< - function(x)
{
#上次观察持续转发(从左到右的系列)
LOCF < - max(which(!is.na(x)))#最后观察继续执行的位置
x [LOCF:length(x)]< - x [LOCF]
return(x)
}
#示例:
LOCF (1,2,3,4,NA,NA))
LOCF(c(1,NA,3,4,NA,NA))
现在,这对于简单的向量非常有用。但是,如果我在数据框中尝试使用它:
a< - data.frame(rep(a ,4),1:4,1:4,c(1,NA,NA,NA))
a
t(apply(a,1,LOCF))#将会搞乱
它将把我的数据框变成一个字符矩阵。
<你可以想象一下在数据框架上做LOCF的方法,而不是把它变成一个矩阵? (我可以使用循环来纠正这个混乱,但是会喜欢一个更优雅的解决方案)
干杯,
Tal
解决方案
这已经存在:
$($)
na.locf(data.frame(rep(a,4),1:4,1:4,c(1,NA,NA,NA) ))
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.
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)
Cheers,
Tal
解决方案
This already exists:
library(zoo)
na.locf(data.frame(rep("a",4), 1:4,1:4, c(1,NA,NA,NA)))
这篇关于最后观察结束在数据框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文