1

I am currently writing a program where the user can give certain weightvalues to certain traits of animals, to assess their relevance. Because the number of traits is dynamic, i.e. users can enter a file with an X number of animals and a Y number of traits, I wished to present the option through a loop.

#A simple input
G <- c("Length", "Width", "Size")

#Creating the base structure. I wish to pack the code as a framed element in the GUI.
require(gWidgets2RGtk2) #Load package
W <- gwindow("Weight Values", visible = TRUE)
WW <- ggroup(cont = W, expand = TRUE, horizontal = FALSE)
w <- gframe("Variables", cont = W, expand = TRUE, horizontal = FALSE)
value_list <- list()

#Creating the dynamic gedits.
for (i in 1:(length(G))) {
   g <- gframe(paste("Trait:", i), cont = w, expand = TRUE)
   a <- gedit("1",cont=g)
   addHandlerKeystroke(a, handler=function(...) { 
   value_list[i] <<- svalue(a)

})
}

#After filling in numbers, the call for the list gives only the latest value.    Not the earlier values 
value_list

Returning value_list gives this. (After filling 4, 5, 6 as the values):

 > value_list
 [[1]]
 NULL

 [[2]]
 NULL

 [[3]]
 [1] "6"

I expected the code to return 4, 5, 6. I have tried to introduce some kind of dynamic listing of vectors for "a", but that only gives errors.

Both suggestions for improvements and approaches are very welcome.

Thanks in advance!

ps: I did take a look at this question before placing this question. However, the looping part seems to cause trouble.

EDIT (30-8-2016):

I would like to thank John for his suggestion. By replacing the content of the subheader "#Creating the dynamic gedits" with:

sapply(1:length(G), FUN = function(i) {
   g <- gframe(paste("Trait:", i), cont = w, expand = TRUE)
   a <- gedit("1", cont=g)
   addHandlerKeystroke(a, handler=function(...) { 
        value_list[i] <<- svalue(a)
   })
})

The code managed to work, without gaining errors. Thank you very much! I am now able to acces the value_list.

Community
  • 1
  • 1
RvB
  • 11
  • 3
  • Try `sapply` and not a for loop. The value of `i` when called is 3, not 1 then 2 then 3. You need to force the i to be local. – jverzani Aug 29 '16 at 20:56
  • Thank you very much, John! I've edited the main post to provide a solution and a functional template for people pondering about similar problems. – RvB Aug 30 '16 at 08:34

0 Answers0