How to take the mean of last 10 values in a column before a missing value using R?

爱⌒轻易说出口 提交于 2019-12-04 13:02:19

You can use sapply and tail together with na.omit as follows:

sapply(mydf[-1], function(x) mean(tail(na.omit(x), 10)))
#   Tree1   Tree2   Tree3 
# 105.017  67.152 152.976 

mydf[-1] says to drop the first column. tail has an argument, n, that lets you specify how many values you want from the end (tail) of your data. Here, we've set it to "10" since you want the last 10 values. Then, assuming that there are no NA values in your actual data from while the trees are alive, you can safely use na.omit on your data.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!