简体   繁体   English

如何在R中定义递归for循环?

[英]How to define a recursive for loop in R?

I have a priorly unknown number of variables, and for each variable I need to define a for loop and perform a series of operations.我有一个先前未知数量的变量,对于每个变量,我需要定义一个 for 循环并执行一系列操作。 For each subsequent variable, I need to define a nested loop inside the previous one, performing the same operations.对于每个后续变量,我需要在前一个变量中定义一个嵌套循环,执行相同的操作。 I guess there must be a way of doing this recursively, but I am struggling with it.我想一定有一种方法可以递归地执行此操作,但我正在为此苦苦挣扎。

Consider for instance the following easy example:例如,考虑以下简单示例:

results = c()
index = 0

for(i in 1:5)
{
  a = i*2
  for(j in 1:5)
  {
    b = a*2 + j
    for(k in 1:5)
    {
      index = index + 1
      c = b*2 + k
      results[index] = c

    }
  }
}

In this example, I would have 3 variables.在这个例子中,我将有 3 个变量。 The loop on j requires information from the loop i, and the loop on k requires information from the loop j. j 上的循环需要循环 i 中的信息,k 上的循环需要循环 j 中的信息。 This is a simplified example of my problem and the operations here are pretty simple.这是我的问题的一个简化示例,这里的操作非常简单。 I am not interested on another way of getting the "results" vector, what I would like to know is if there is a way to recursevily do this operations for an unknown number of variables, lets say 10 variables, so that I do not need to nest manually 10 loops.我对获取“结果”向量的另一种方式不感兴趣,我想知道的是是否有一种方法可以递归地对未知数量的变量执行此操作,比如说 10 个变量,这样我就不需要了手动嵌套 10 个循环。

Here is one approach that you might be able to modify for your situation...这是您可以根据自己的情况修改的一种方法......

results <- 0                                     #initialise
for(level in 1:3){                               #3 nested loops - change as required
  results <- c(                                  #converts output to a vector
               outer(results,                    #results so far
                     1:5,                        #as in your loops
                     FUN = function(x,y) {x*2+y} #as in your loops
                     )
               ) 
}

The two problems with this are与此有关的两个问题是

a) that your formula is different in the first (outer) loop, and a) 您的公式在第一个(外部)循环中不同,并且

b) the order of results is different from yours b) 结果的顺序与您的不同

However, you might be able to find workarounds for these depending on your actual problem.但是,您或许可以根据实际问题找到解决这些问题的方法。

I have tried to change the code so that it is a function that allows to define how many iterations need to happen.我试图更改代码,使其成为一个允许定义需要发生多少迭代的函数。

library(tidyverse)


fc <- function(i_end, j_end, k_end){

  i <- 1:i_end
  j <- 1:j_end
  k <- 1:k_end

  df <- crossing(i, j, k) %>%
    mutate(
      a = i*2,
      b = a*2 + j,
      c = b*2 + k,
      index = row_number())

  df

}

fc(5,5,5)

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

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