Welcome, Guest
Username: Password: Remember me

TOPIC: POTM (Jan-2016): The Menu Command

POTM (Jan-2016): The Menu Command 5 months 2 weeks ago #57

The January “POTM” should perhaps be called a “PPOTM” (Practical Programming of the Month).

The R menu command will take a data structure (e.g. a list of all “*.csv” file names found in the current working directory, or a list of column headings present in a data table) and list it out as a numbered menu of choices (e.g., a list of five items would show a menu with options 1 – 5 displayed). When the script is running, the number you type into this menu prompt will then return the value of that entry for further action within the script (e.g., loading that data file, plotting the selected variable). Typing a zero into the menu prompt will exit the menu with a zero value, which can be used to signal exit from loops.
This month’s example uses the menu command to let the user select from a list of “*.csv” data files load, and then a second menu call lets the user select from a list of variables (loaded from that selected data file) and plots the user selected variable as a simple time series XY plot. Typing a zero at any menu prompt will exit you to the previous menu (or exit the script). The menu command could also be used to select between multiple site maps, different plot types, and a whole variety of other options.

Some very important notes before you begin:
  1. This script uses example data files from the morning session of the 2015 workshop. (They are also attached to this posting.) These files must be in your current working directory for the script to see them, otherwise there are no *.csv files for the menu to list and it will exit. (You can modify this script to work with your own data structures and/or files.)
  2. You probably do NOT want to run this script one line at a time, mainly because of the “while” loops. (R will wait until the full “while” loop is loaded before operating in the console window, which in this script means you have to load almost every line of the script before anything actually happens.) In RStudio, you can use the “Source” button (the icon in the far upper right of the script window) to run the entire script with one click. You can all use the “source” command from within the console. The nice thing about the “Source” button in RStudio is that it automatically rewinds to the beginning of the script and it automatically selects the console window for you (re: Item #4 below).
  3. If you do run one line at a time, R may get stuck in an infinite loop because it is waiting for the end of the “while” loop coding to appear. At this point the console window may not respond at all. Todd found that you had to select the “Terminate R” option from the Session tab in RStudio, as the “Restart R” did not work most of the time. You may also trying typing a bunch of “}” in the console window to try to close out the “while” loop. This kind of error will likely only happen while you are modifying the script, and it seems to only happen when the “}” closing the main while loop can’t be found.
  4. Also, if you do run one line at a time, you may need to click on the console window (to select it versus your script editing window) so that your typed menu selections actually happen in the console window rather than your script editing window.

Here is the script:
# PPOTM:  Practical-Programming Of The Month (2016 January)
# iMAINloop:  Continue asking users "what file to load" until they type a zero.
iMAINloop <- 0;
while (iMAINloop < 1 ) {
  # Below creates a list of all files (in the current working directory) of pattern *.csv
  # Note that you can set  path="xxxx" to look in a different folder area
  filenames <- list.files(pattern = ".csv")
  # Below assigns the filename (text) assigned by the user's menu selection to variable "filename"
  filename <- filenames[menu(filenames,title = "Select a file (enter ZERO to quit):")];
  # If the filename was less than 1, a zero was typed (or no CSV files existed)
  if (length(filename) < 1) {
    iMAINloop <- 1; # exit iMAINloop
  } else {
    # Below loads the CSV file into variable "loadDATA"    
    loadDATA <- read.csv(filename, header=TRUE);
    # iMENUloop:  Continue asking what variable to plot
    iMENUloop <- 0;
    while (iMENUloop < 1 ) {
      # Below passes the COLUMN NUMBER (not the text) of the menu-selected variable      
      menuVAR <- menu(names(loadDATA),title="Pick a variable (0 to exit):");
      if ( menuVAR < 1 ) {
        iMENUloop <- 1; # A zero was typed (or no vars found)
      } else {
        # IMPORTANT:  Below assumes the first column is month/day/4-digit-year DATES  
        xDATES <- as.Date(loadDATA[[1]],"%m/%d/%Y")
        # Below takes the date from column menuVAR and loads it into yDATA, without any column header [[]]
        yDATA <- loadDATA[[menuVAR]]
        # Below grabs the select column's label (column name)
        ylabTEXT <- colnames(loadDATA[menuVAR])
        # Below grabs the loaded filename and pastes it together with the variable (ylabTEXT)
        mainTEXT <- paste(filename,ylabTEXT,sep=":   ")
        # Below plots the variables vs date (no thrills)
        # plot(xDATES,yDATA)
        # Below plots the menu-selected variable vs date 
        # The main plot title is assigned to the filename loaded
        # The Y label is assigned the variable header name
        # The dots are green (#00ff00)
        plot(xDATES,yDATA,main=mainTEXT, xlab="Date", ylab=ylabTEXT, col="#00ff00")
      # Below is the closing parenthesis for the iMENUloop
  #  Un-comment the line below to exit immediately (not pick another data file to load)
  #  iMAINloop <- 1 ;
  # Below is the closing parenthesis for the iMAINloop  

The above script is fairly well internally commented. Most of the plotting and data transformation steps were taken from the morning session of the 2015 NERRS "R" workshop. (So look there for additional information or explanation.)

You can directly load the script above using the command:

The zip file below contains four *.csv files to use with this example.
Last Edit: 5 months 2 weeks ago by Marcus Beck. Reason: kittens
The administrator has disabled public write access.

POTM (Jan-2016): The Menu Command 5 months 2 weeks ago #58

  • Marcus Beck
  • Offline
  • Administrator
  • Posts: 32
  • Thank you received: 5
  • Karma: 4
Nice code, Todd. I haven't seen the menu function before... it's nice to know that this option is available! It would be cool to include this in future SWMPr workshops.
The administrator has disabled public write access.
The following user(s) said Thank You: Todd.OBrien

POTM (Jan-2016): The Menu Command 5 months 1 week ago #73

I'm just seeing this now, Todd, but this is really cool! Thanks!
The administrator has disabled public write access.
Time to create page: 0.150 seconds
Powered by Kunena Forum