R:是否可以在同一列上使用mutate + lag? [英] R: Is it possible to use mutate+lag with the same column?
本文介绍了R:是否可以在同一列上使用mutate + lag?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在R中复制以下公式:
I'm trying to replicate the following formula in R:
Xt = Xt-1 * b + Zt *(1-b)
Xt = Xt-1 * b + Zt * (1-b)
我正在使用以下代码
t %>%
mutate(x= ifelse(week == 1, z, NaN)) %>% # Initial value for the first lag
mutate(x= ifelse(week != 1, lag(x,1 ,default = 0) * b + z, z)
但是我从第二个元素中得到了所有的NaN.
But I get all NaN except from the second element.
z b x
(dbl) (dbl) (dbl)
1 168.895 0.9 168.8950
2 20.304 0.9 131.7472
3 14.943 0.9 NA
4 11.028 0.9 NA
5 8.295 0.9 NA
6 8.024 0.9 NA
7 6.872 0.9 NA
8 7.035 0.9 NA
9 4.399 0.9 NA
10 4.158 0.9 NA
这在excel中非常简单,但是我必须在R中完成,您有什么方法吗?
This is fairly simple in excel but I must do it in R, Do you have any approaches?
可复制的示例:
set.seed(2)
t = data.frame(week = seq(1:52),
z = runif(52, 0, 100),
b = 0.2)
推荐答案
由于@Frank和@docendo discimus,我发现解决方案正在运行以下循环
I found the solution running the following loop, thanks to @Frank and @docendo discimus
for (row in 2:dim(t)[1]) {
t[row,] <- mutate(t[1:row,], x= lag(x,1) * b + z * (1 - b))[row,]
}
这篇关于R:是否可以在同一列上使用mutate + lag?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文