如何定义一定数量的嵌套for循环(基于R应用中的输入长度)?
这里是上下文:我在一个R闪亮的web应用程序上工作。用户上传一个数据帧。然后他用selectInput选择一定数量的列。所选列的数量可以从一列到六列不等 基于这些列的数量,我想自动为循环生成适当数量的嵌套。当时,我通过测试每一个可能选择的列数来使用if()条件。 我希望传递选定列的每个唯一值。这使得我的代码非常长:如何定义一定数量的嵌套for循环(基于R应用中的输入长度)?,r,for-loop,input,shiny,nested-loops,R,For Loop,Input,Shiny,Nested Loops,这里是上下文:我在一个R闪亮的web应用程序上工作。用户上传一个数据帧。然后他用selectInput选择一定数量的列。所选列的数量可以从一列到六列不等 基于这些列的数量,我想自动为循环生成适当数量的嵌套。当时,我通过测试每一个可能选择的列数来使用if()条件。 我希望传递选定列的每个唯一值。这使得我的代码非常长: my_columns = input$colnames #The user selects column names if(length(mycolumns) == 1){ fo
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循环
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
循环的主体是什么。最内部循环的预期输出应该是什么?您无法使用具有定义数量的aguments的函数:myfun(var1,var2,var3)
如果仅在两个for循环中应用,将无法工作,因为缺少参数var3。你能详细说明你想在所有这些for循环中做什么吗?