简体   繁体   English

R 如何将具有递归滞后的 for 循环转换为 function?

[英]R How to transform a for loop with recursive lag into a function?

I can compute a recursive variable with a for loop like this:我可以使用这样的 for 循环计算递归变量:

df <- as.data.frame(cbind(1:10))

df$it <- NA
for(i in 1:length(df$V1)) {
  df$it <- 0.5*df$V1 + dplyr::lag(df$it, default = 0)
  }
df

But how can I do this with a function on the fly?但是我怎么能在运行中使用 function 做到这一点? The following produces an error "C stack usage 15924032 is too close to the limit":以下产生错误“C 堆栈使用 15924032 太接近限制”:

adstwm <- function(x){
  0.5*x + adstwm(dplyr::lag(x, default = 0))
  }
adstwm(df$V1)

I guess I need to define a stop for the process, but how?我想我需要为该过程定义一个停止,但是如何?

You can use the cumulative sum to achieve the desired result.您可以使用累积和来实现所需的结果。 This sums all preceding values in a vector which is effectively the same as your recursive loop:这将向量中的所有先前值相加,该向量实际上与您的递归循环相同:

df$it_2 <- cumsum(0.5*df$V1)

If you do want to make recursive function, for example to address the comment below you can include an if statement that will make it stop:如果您确实想要递归 function,例如,为了解决下面的评论,您可以包含一个 if 语句,使其停止:

function_it <- function(vector, length) {
  if (length == 1) 0.5*vector[length]
  else 0.5*vector[length] + 0.1*function_it(vector, length-1)
}

df$it <- NA
for(i in 1:length(df$V1)) { 
  df$it[i] <- function_it(df$V1,i)
} 
df 

However, you still need the for loop since the function is not vectorised so not sure if it really helps.但是,您仍然需要 for 循环,因为 function 未矢量化,因此不确定它是否真的有帮助。

I can put the lagged for loop into the function without recursing the function:我可以将滞后的 for 循环放入 function 而不递归 function:

df <- as.data.frame(cbind(1:10))
func.it2 <- function(x){
  df$it2 <- NA
  for(i in 1:length(df$V1)) {
    df$it2 <- 0.5*df$V1 + 0.1*dplyr::lag(df$it2, default = 0)
  }
  df$it2
  }
func.it2(df$V1)
df
df$it2 <- func.it2(df$V1)
df

That works.这样可行。 But why is df$it2 not available as a variable in df until I declare it (second last line) although it was already available in the for loop (line 5)?但是为什么 df$it2 在我声明它(倒数第二行)之前不能作为 df 中的变量使用,尽管它已经在 for 循环中可用(第 5 行)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM