【问题标题】:How to define a certain number of nested for-loops (based on input length in R Shiny app)?如何定义一定数量的嵌套 for 循环(基于 R Shiny 应用程序中的输入长度)?
【发布时间】:2021-08-20 10:31:05
【问题描述】:

这里是上下文:我在一个 R 闪亮的 Web 应用程序上工作。用户上传一个数据框。然后,他使用 selectInput 选择一定 n 个列。所选的列数可以从 1 到 6 不等。

基于此列数,我想自动生成适当数量的嵌套 for 循环。那时,我使用 if() 条件来测试每个可能选择的列数。 我想传递所选每一列的每个唯一值。这使我的代码很长:

my_columns = input$colnames #The user selects column names

if(length(mycolumns) == 1){
 for(var1 in unique(mydataframe[,my_columns[1]])){
   ...
 }
}

if(length(mycolumns) == 2){
 for(var1 in unique(mydataframe[,my_columns[1]])){
    for(var2 in unique(mydataframe[,my_columns[2]])){
     ...
    }
  }
}

if(length(mycolumns) == 3){
 for(var1 in unique(mydataframe[,my_columns[1]])){
   for(var2 in unique(mydataframe[,my_columns[2]])){
     for(var3 in unique(mydataframe[,my_columns[3]])){
      ...
     }
   }
 }
}

等等……

有没有办法避免这种情况?

谢谢

【问题讨论】:

    标签: r for-loop input shiny nested-loops


    【解决方案1】:

    如果我弄错了,请纠正我,但您似乎计算了一些需要涵盖所选列的所有可能值组合的东西。

    在这种情况下,R 不需要嵌套的 for 循环

    my_columns <- data.frame(
      "A" = c(1,2,3),
      "B" = c(11,12,13),
      "C" = c(21,22,23))
    
    # find all unique values per column
    list_uniques <- lapply(seq_along(my_columns),
                           function(x){unique(my_columns[[x]])}
                           )
    
    # find out all possible combinations of the given values
    # the output is a dataframe
    all_combinations <- expand.grid(list_uniques)
    
    # Now you can iterate over the frame and do something with them
    
    # example rowsums
    rowSums(all_combinations) # vectorized functions like this are faster
    
    # example custom function
    apply(all_combinations,
                  MARGIN = 1, # iterate rowwise
                  # you can now use your own function
                  # the input i is a row as a named vector
                  FUN = function(i){paste(i,collapse = " and ")})
    # This function will output:
    # "1 and 11 and 21" "2 and 11 and 21" ....
    

    【讨论】:

    • 谢谢你,你解释的内容在未来对其他用途非常有用,但我认为它不能解决我当前的问题......我想对我的数据应用过滤器但我的问题太宽泛了
    • 我不明白你的 for 循环的主体是什么。最内层循环的预期输出应该是什么?您无法使用具有定义数量的参数的函数:myfun(var1,var2,var3) 仅在两个 for 循环中应用时将不起作用,因为缺少参数 var3。您能否详细说明您想在所有这些 for 循环中做什么?
    猜你喜欢
    • 2019-03-21
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    相关资源
    最近更新 更多