Designing dialog box in R - r

How can we a design a dialog box in R?
In my mind I have something in which an alert message is displayed or where we can write a certain value and then clicking a button it performs some computation... is that possible within the R workspace?

Something like this should work
library("tcltk")
button <- tkmessageBox(title='Message',message='Error x!',type='ok')
button <- tclvalue(button)
if(button == 'ok'){
#do something
}

winDialog also works:
library(utils)
answer<-winDialog("yesno", "was the suggestion useful?")
if (answer=='YES') {print('good!')} else {print('sorry')}
Just try to copy the full code and paste it into your R console: a dialog box will come out and a final output ('good!' or 'sorry') will appear depending on the answer you click.

You could try:
utils: select.list if you are choosing from pre-set alternatives. edit is more general, but less polished.
gWidgets: Interfaces with either tcltk or RGtk2 to produce dialogues. gmessage and ginput are probably what you are looking for.

Related

RStudio not showing output in Console when using a variable?

Currently learning RStudio but for some reason my Console isn't outputting my code? Not sure if there was a setting I may have toggled but it seems to only affect me when I have a variable in my code?
For example:
when working the ToothGrowth dataset
data("ToothGrowth")
View(ToothGrowth)
This executes and I can view the table of the data in a separate tab.
However, when I try to filter it
data("ToothGrowth")
View(ToothGrowth)
filtered_tg = filter(ToothGrowth, dose=0.5)
View(filtered_tg)
Nothing Returns, a formatted table doesn't open and an empty line is returned in the console window.
This is just one example, even when i try something as simple as
number = 10
number
I would expect, in return;
[1] 10
But console is empty.
Looking for solutions online, I've seen maybe i didn't close a bracket or parenthesis and to include CloseAllConnections() if there was a '+' showing in the console (which there isn't).
Working on rstudio cloud so is there a reset somewhere that I could possibly try?
Thanks for any and all help!
I changed the function as follows:
filtered_tg = filter(ToothGrowth, dose=="0.5")
View(filtered_tg)
After running these commands it was viewed as the table of the data in a separate tab 👇
Output

Editing or Viewing data frame in R Console

I can see the entire data frame in the console. Is there any possible way or any function to view data frame in the R-Console (Editing similar to that of Excel) so that I should be able to edit the data manually?
S3 method for class 'data.frame'
You can use:
edit(name, factor.mode = c("character", "numeric"),
edit.row.names = any(row.names(name) != 1:nrow(name)), ...)
Example:
edit(your_dataframe)
You can go through in detail with the help of this link - Here
You really can use edit() or view().
But maybe, if you dataset isn't big enough, if you prefer to use Excel, you can use this function below:
library(xlsx)
view.excel<-function(inputDF,nrows=5000){
if (class(inputDF)!="data.frame"){
stop("ERROR: <inputDF> class is not \"data.frame\"")
}
if(nrow(inputDF)>5000 & nrows!=-1){
inputDF=inputDF[1:nrows,]
}
tempPath=tempfile(fileext='.xlsx')
write.xlsx(inputDF,tempPath)
system(paste0('open ',tempPath))
return(invisible(tempPath))
}
I've defined this function to help me with some tasks in R...
Basically, you only need to pass a DataFrame to the function as a parameter. The function by default display a maximum of 5000 rows (you can set the parameter nrows = -1 to view all the rows, but it may be slow).
This function opens your DataFrame in Excel and returns the path where your temporary view was saved. If you wanna save and load your temporary view, after changing something directly with Excel, you can load again your data frame with:
# Open a view in excel
tempPath <- view.excel(initialDF, nrows=-1)
# Load the file of the Excel View in the new DataFrame modifiedDF
modifiedDF <- read.xlsx(tempPath)
This function may works well in Linux, Windows or Mac.
You can view the dataframe with View():
View(df)
As #David Arenburg says, you can also open your dataframe in an editable view, but be warned this is slow:
edit(df)
For updates/changes to affect the dataframe use:
df <- edit(df)
Since a lot of people are using (and developing in) RStudio and Shiny nowadays, things have become far more convenient for R users.
You should look at the rhandsontable package.
There is also very nice Shiny implementation of rhandsontable, from a blog I stumbled upon: https://stla.github.io/stlapblog/posts/shiny_editTable.html. It's not using the console, but it is anyway super slick:
(A few years later) This may be worth trying if you use RStudio: It seems to support all data types. I did not use it extensively but helped me ocassionally:
https://cran.r-project.org/web/packages/editData/README.html
It shows an editing dialog by default. If your dataframe is big you can browse to http://127.0.0.1:7212 while the dialog is being shown, to get a resizable editing view.
You can view and edit a dataframe using with the fix() function:
# Open the mtcars dataframe for editing:
fix(mtcars)
# Edit and close.
# This produces the same result:
mtcars <- edit(mtcars)
# But it is a longer command to write.

Viewing more than 1000 rows in RStudio

In RStudio when you use the View() function, it only allows you to see up to 1000 rows. Is there any way to see more than that. I know it is possible to subset the viewing and see rows 1000-2000 for example, but I would want to be able to see 1-2000. The best I could find was a comment about a year ago saying that it wasn't possible at the time but they were planning on fixing this.
Here's an example (note: I'm guessing you will have to run this in RStudio).
rstudio <- (1:2000)
View(rstudio)
The View command is specifically for the little helper window. You can easily view the full value in the actual console window. If you want the same layout, use cbind.
cbind(rstudio)
which in fact will even give you the same nice row-numbering setup
And if that's too cumbersome
pview <- function(x, rows=100) {
if (length(x) > rows)
print(cbind(x))
else
print(cbind(head(x, rows/2)))
print(cbind(tail(x, rows/2)))
}
pview(rstudio, 1998)
you will need to clean that up to get the row names to lineup
You can change this setting, for instance:
options(max.print=5000)

How Do I Stop An R gWidgets Script Exiting

I am using the gWidgets toolkit to create a GUI in an R script that is run using Rscript.
When the GUI is created, the script exits.
I can prevent this with a while(TRUE){Sys.sleep(9999)} loop at the end of the script but that seems hacky.
Is there a better way of telling R to exit only when the GUI is closed, or at least to enter the REPL once the GUI is constructed?
You might be able to adapt gbasicdialog for your needs. This constructor creates a modal container from which you can spawn other windows. Here is an example:
library(gWidgets)
options(guiToolkit="RGtk2")
require(fortunes) # just for fun
hold_it <- gbasicdialog(do.buttons=FALSE)
b <- gbutton("click me for a message", cont=hold_it, handler=function(h,...) {
gmessage(paste(fortune(), collapse="\n"), parent=hold_it)
})
visible(hold_it, TRUE)
The same works for the "tcltk" toolkit. It uses pretty much what Greg suggests can be done.
This subject may be closed but as a newbie to gwidgets, I have been confronted with. The solution given by jverzani is obviously a solution. I have chosen another one, not using any supplementary dialog, just because I don't want one, no other reason at all...
In the handler of the gwindow, after disposal I remove the variable from the environment:
handler = function(h,...) {dispose(EDFAnalysis$w); rm(w,envir=EDFAnalysis)}
where EDFAnalysis is the environment of my script... and w is the main gwindow.
Then, at the end of my script I added:
while(exists("w",EDFAnalysis)){Sys.sleep(5)}
of course, smaller value than 5 or greater value can be used. In my case, 5 s is sufficient and not for ever... :-)
The standard way of dealing with this is to request user input to continue. This one-liner will do the trick.
EDIT: readline only works under interactive use, so I've swapped it for scan, which is a little less pretty.
pause_for_input <- function()
{
message("Press ENTER to continue")
invisible(scan(n = 0, quiet = TRUE))
}
So you script should look like
#Create you GUI
#Whatever else
pause_for_input()
If you are using the tcltk package instead of gWidgets then you could possibly use the tkwait.window function from tcltk to tell the script to wait until the gui window goes away before continuing the script.
A good way to do it, I've found, is to use the gtkMain() function in the RGtk2 library. This simply keeps the main loop running until gtkMainQuit() is called.
For completeness: ozjimbob already gave the answer for a most "clean" way how to do it.
The answer of ffeschet did not work with me, neither on Unix nor on Windows.
Hence, in the main "launching" script, you have to at least have these entries:
options("guiToolkit"="RGtk2")
library(RGtk2)
library(gWidgets)
library(gWidgetsRGtk2)
StartMyGUI()
gtkMain()
In the "child" process "StartMyGUI()", your code could e.g. look like this:
StartMyGUI <- function(handler=function(h,...) {
dispose(h$obj)
}) {
window <- gwindow("Hello")
group <- ggroup(container = window)
glabel("Hello World!", container=group, expand=TRUE)
# A group to organize the buttons
button.group <- ggroup(container = group)
# Push buttons to right
addSpring(button.group)
gbutton("OK", handler=handler, container=button.group)
gbutton("Cancel", handler = function(h,...) {
dispose(window)
gtkMainQuit()
},
container=button.group)
return()
}
It is only when the user hits the "Cancel" button that gtkMainQuit() will be called, which exits the mother process in the main "launching" script.

Making a series of plots that proceed by a click

In the example below I would like to be able to control when I go to the next plot by a using mouse click (or keyboard entry)
for (i in 1:5){
plot(1:i)
Sys.sleep(1)
#add something here that requests mouse click to proceed
}
Is this possible? There is a setting in the X11() help file caled 'clickToConfirm' but I can't work out what that does.
It would also be helpful to me to be to be able to scroll back and forth through plots using the arrow keys. Is this possible?
Currently if I need to look at lots of plots I output them into a big .pdf file and scroll though them all there, but that is a bit cumbersome.
Thanks
Tom
In R, that would be done by setting par(ask=TRUE). Try the following code, which shows how to reset the par when exiting the function :
op <- par(ask=TRUE)
for (i in 1:5){
plot(1:i)
}
par(op)
If you want to keep a history to browse through, you can either open a window and click on recording in the History menu, or you can open the window yourself with the history on. Demonstrated in a function :
plot.fun <- function(){
windows(record=TRUE) # opens a window and starts recording
op <- par(ask=TRUE)
on.exit(par(op))
for (i in 1:5){
plot(1:i)
}
windows.options(record=FALSE) #stops recording.
}
plot.fun()
This will however keep all previous plots in the history for browsing as well, so if you run this code 3 times you'll have 15 plots in the plot history. Also note that the open plot window will keep on recording until you turn off the recording in the menu.
You can play with the plot history, as you'll have a variable .SavedPlots which contains the saved plot history. It can be cleared using the menu History > clear history in the plot window. If you want to clear the history from the console, you could hack that by
.SavedPlots <- NULL
But I advise you not to do this, as changing the .SavedPlots variable can cause R to crash.
See also ?windows and ?recordPlot for a bit more information. But as you're getting close to the internal code of R, be warned that you can get pretty awkward behaviour if you start playing around with these things.
For scrolling back and forth between plots using the arrow keys: it depends on the platform/R interface.
Windows: there is a recording function (see Q5 of the R for Windows FAQ) which uses Page Up/Page Down
MacOS: under the standard GUI, the Quartz window has Apple-left and Apple-right arrow
under the standard Unix (no-GUI) interface, things are more limited. You can use RStudio (which has a lot of buzz right now) ... I would have thought that JGR would have plot history as well, but it doesn't seem to ...
You can use locator - now plots change on click
for (i in 1:5){
plot(1:i)
locator(1)
}

Resources