用上面行中的值填充数据框 [英] Fill in data frame with values from rows above
问题描述
说我有一个像这样的数据框:
Say I have a data frame like this:
ID, ID_2, FIRST, VALUE
-----------------------
'a', 'aa', TRUE, 2
'a', 'ab', FALSE, NA
'a', 'ac', FALSE, NA
'b', 'aa', TRUE, 5
'b', 'ab', FALSE, NA
因此,每个ID仅将FIRST = TRUE设置一次。 ID_2可以在ID之间重复,但不必重复。
So VALUE is only set for FIRST = TRUE once per ID. ID_2 may be duplicate between IDs, but doesn't have to.
如何将每个ID的第一行中的数字放入该ID的所有行中,例如VALUE列变成2、2、2、5、5?
How do I put the numbers from the first rows of each ID into all rows of that ID, such that the VALUE column becomes 2, 2, 2, 5, 5?
我知道我可以简单地使用for循环遍历所有ID,但是我正在寻找一个
I know I could simply loop over all IDs with a for loop, but I am looking for a more efficient way.
推荐答案
如果您只需要结转VALUE列中的值,那么我认为您可以使用< zoo 包中的code> na.lofc()函数。这是一个示例:
If you need only to carry forward the values from the VALUE column, then I think you can use na.lofc()
function from zoo package. Here is an example:
a<-c(1,NA,NA,2,NA)
na.locf(a)
[1] 1 1 1 2 2
这篇关于用上面行中的值填充数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!