community
cancel
Showing results for 
Search instead for 
Did you mean: 

Alteryx designer Discussions

Find answers, ask questions, and share expertise about Alteryx Designer.
Community v19.6

Looks aren't everything... But the latest Community refresh looks darn good!

Learn More

Running a loop with R code and appending the results

Highlighted
Asteroid

Hi

 

I have an input data like below

 

NameIDScore1Score2Total
J245122335

 

i am passing this into an R code in alteryx workflow and i use randomly generated weights to calculate weighted total. Now i would like to run the R code 10 times, each time generating new random weights and calculate 10 weighted total, then calculate the lowest weight and output it as final result. 

 

my desired output

 

NameIDScore1Score2Totalweighted total
J24512233514.3
J2451223359.9
J24512233516.1
J24512233510.5
J24512233512.2
J2451223358
J24512233511.3
J24512233515.5
J2451223359.1
J24512233513.6

 

After generating the above output table, my final result will be the one with lowest weighted total (8)

I have attached the workflow herewith. 

 

Any suggestion on how to do this in a looped manner?

Alteryx Certified Partner
Alteryx Certified Partner

Hi @GaRaGe 

 

Yes you could turn it into a batch macro or iterative macro.

 

I'm not being able to see your R tool, since I don't have it installed, but it's pretty easy. Here's a mockup of how your macro would look:

 

 

R Tool.PNG

This is an iterative macro example.

 

Select tool before the Loop Output is so you take the field of Weight that you created, because the loop output will feed the input of the next iteration (it must have the same columns).

 

Numeric Drop Down is to give you the choice of how many times you want to run the macro.

 

R tool2.PNG


Then you use your macro, a Sort tool to put the minimum value of weight on top, and sample tool to select first record.

 

capture.PNG

 

Cheers.

ACE Emeritus
ACE Emeritus

Hi @GaRaGe,

 

Since you're doing R anyway, you could include the logic in your R code:

input<-read.Alteryx("#1",mode="data.frame")

set.seed(1234)

min_weight <- input$Score1 + input$Score2

for (i in 1:10) {

  weights <- runif(2,min=0.1,max=0.9) 
weighted_tot <- (input$Score1*weights[1]) + (input$Score2*weights[2]) if (weighted_tot < min_weight) { min_weight <- weighted_tot } } input$weighted_tot <- min_weight write.Alteryx(input,1) write.Alteryx(as.data.frame(weights),2)

I'm sure that can be cleaned up a bit, but that's the basic idea.

 

Hope that helps!

John 

 

Labels