本文介绍了在R中迭代地用先前的值填充NA行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Say you have something like this across various weeks in a given df:
DoW Value
Mon 1234
Tue NA
Wed 5678
Thu 9123
Fri 4567
Sat 8912
Sun 3456
I'd like to fill every Tuesday's NA with Monday's value of it's correspondent week. How can I do this, preferably with the least amount of code possible?
Thanks.
解决方案
What about this ?
mydf <- structure(list(DoW = c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sun"), Value = c(1234L, NA, 5678L, 9123L, 4567L, 8912L, 3456L
)), .Names = c("DoW", "Value"), class = "data.frame", row.names = c(NA,
-7L))
tuesd_na <- which(mydf$DoW == "Tue" & is.na(mydf$Value))
mydf$Value[tuesd_na] <- mydf$Value[tuesd_na - 1]
mydf
#> DoW Value
#> 1 Mon 1234
#> 2 Tue 1234
#> 3 Wed 5678
#> 4 Thu 9123
#> 5 Fri 4567
#> 6 Sat 8912
#> 7 Sun 3456
这篇关于在R中迭代地用先前的值填充NA行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!