Text Editor Won't Close and Crashes in R - r

I am trying to run a model in R using PVA and transition matrices. Whenever I run a line and the text editor spreadsheet pops up, I am able to edit the data but it won't close and just freezes so I have to shut everything down. I've tried restarting several times but I can't get it to work and I need to be able to run this line of code. Specifically it happens when I run "supplement_matrix <- make.supplement.matrix(num.stages)" Here is my code:
library(popbio)
library(reshape2)
library(expm)
multiyear.stages <- read.csv('multiyear_stages_longform.csv')
head(multiyear.stages)
unique(multiyear.stages$Survey)
nrow(multiyear.stages[multiyear.stages$Survey==1,])
nrow(multiyear.stages[multiyear.stages$Survey==1&multiyear.stages$Stage==1,])
nrow(multiyear.stages[multiyear.stages$Survey==2,])
nrow(multiyear.stages[multiyear.stages$Survey==2&multiyear.stages$Stage==2,])
nrow(multiyear.stages[multiyear.stages$Survey==1&multiyear.stages$Stage<=2,])
nrow(multiyear.stages[multiyear.stages$Survey<=2&multiyear.stages$Stage==1,])
nrow(multiyear.stages[multiyear.stages$Survey==2&multiyear.stages$Stage==2,])
plants<-dcast(multiyear.stages, ID~Survey, value.var="Stage", fill=-1,
fun.aggregate=mean)
head(plants)
nrow(plants[plants$"1"==1&plants$"2"==2,])
nrow(plants[plants$"1"==1&plants$"2"==0,])
nrow(plants[plants$"1"==1&plants$"2"==1,])
nrow(plants[plants$"1"==1&plants$"2"==3,])
nrow(plants[plants$"1"==2&plants$"2"==0,])
nrow(plants[plants$"1"==2&plants$"2"==1,])
nrow(plants[plants$"1"==2&plants$"2"==2,])
nrow(plants[plants$"1"==2&plants$"2"==3,])
nrow(plants[plants$"1"==3&plants$"2"==1,])
nrow(plants[plants$"1"==3&plants$"2"==2,])
nrow(plants[plants$"1"==3&plants$"2"==3,])
nrow(plants[plants$"2"==-1&plants$"3"==1,])
nrow(plants[plants$"2"==1&plants$"3"==0,])
nrow(plants[plants$"2"==1&plants$"3"==1,])
nrow(plants[plants$"2"==1&plants$"3"==2,])
nrow(plants[plants$"2"==1&plants$"3"==3,])
nrow(plants[plants$"2"==2&plants$"3"==0,])
nrow(plants[plants$"2"==2&plants$"3"==1,])
nrow(plants[plants$"2"==2&plants$"3"==2,])
nrow(plants[plants$"2"==3&plants$"3"==3,])
nrow(plants[plants$"2"==3&plants$"3"==0,])
nrow(plants[plants$"2"==3&plants$"3"==1,])
nrow(plants[plants$"2"==3&plants$"3"==2,])
nrow(plants[plants$"2"==3&plants$"3"==3,])
nrow(plants[plants$"1"==3,])
A<-cbind(c(0.317,0.384,0.017), c(0.071,0.592,0.195), c(0.02,0.76,0.1))
N0<-c(40,136,38)
N0 %*% A
source('PVA_source.R')
num.stages<-3
num.iter<-50
num.years<-50
num.iter<-10
num.years<-10
quasi_extinction_threshold<-10
carrying_capacity<-1000
number_of_plants_in_year_1_Stage1 <-cbind(c(19), c(12), c(1))
transition_matrix<-cbind(c(0.317,0.384,0.017), c(0.071,0.592,0.195),
c(0.02,0.76,0.1))
fertility <- c(2.475)
supplement_matrix <- make.supplement.matrix(num.stages)
Here are links to the data I'm using
https://drive.google.com/file/d/0BwRwgnqxDOlxUWNyS25FYVpOZFk/view?usp=sharing
https://drive.google.com/file/d/0BwRwgnqxDOlxZXUzX2EwM2NOZEU/view?usp=sharing

It's hard to diagnose the problem, because I can't replicate it (it runs fine for me). However, you can work around it.
Here's the function from that PVA script that's freezing your system:
make.supplement.matrix<-function(num.stages){
supplement <- matrix(0,nrow=num.stages,,ncol=1,
dimnames=list(paste('stage',1:num.stages),'Number of extra plants to plant each year')
)
supplement <- edit(supplement)
supplement
}
Instead of using it, why not just run:
supplement <- matrix(0,nrow=num.stages,,ncol=1,
dimnames=list(paste('stage',1:num.stages),'Number of extra plants to plant each year')
)
then manually edit (in your script or interactive console) the matrix called supplement any way you please?

Related

Is there a way to let the console in RStudio produce time stamps? [duplicate]

I wonder if there is a way to display the current time in the R command line, like in MS DOS, we can use
Prompt $T $P$G
to include the time clock in every prompt line.
Something like
options(prompt=paste(format(Sys.time(), "%H:%M:%S"),"> "))
will do it, but then it is fixed at the time it was set. I'm not sure how to make it update automatically.
Chase points the right way as options("prompt"=...) can be used for this. But his solutions adds a constant time expression which is not what we want.
The documentation for the function taskCallbackManager has the rest:
R> h <- taskCallbackManager()
R> h$add(function(expr, value, ok, visible) {
+ options("prompt"=format(Sys.time(), "%H:%M:%S> "));
+ return(TRUE) },
+ name = "simpleHandler")
[1] "simpleHandler"
07:25:42> a <- 2
07:25:48>
We register a callback that gets evaluated after each command completes. That does the trick. More fancy documentation is in this document from the R developer site.
None of the other methods, which are based on callbacks, will update the prompt unless a top-level command is executed. So, pressing return in the console will not create a change. Such is the nature of R's standard callback handling.
If you install the tcltk2 package, you can set up a task scheduler that changes the option() as follows:
library(tcltk2)
tclTaskSchedule(1000, {options(prompt=paste(Sys.time(),"> "))}, id = "ticktock", redo = TRUE)
Voila, something like the MS DOS prompt.
NB: Inspiration came from this answer.
Note 1: The wait time (1000 in this case) refers to the # of milliseconds, not seconds. You might adjust it downward when sub-second resolution is somehow useful.
Here is an alternative callback solution:
updatePrompt <- function(...) {options(prompt=paste(Sys.time(),"> ")); return(TRUE)}
addTaskCallback(updatePrompt)
This works the same as Dirk's method, but the syntax is a bit simpler to me.
You can change the default character that is displayed through the options() command. You may want to try something like this:
options(prompt = paste(Sys.time(), ">"))
Check out the help page for ?options for a full list of things you can set. It is a very useful thing to know about!
Assuming this is something you want to do for every R session, consider moving that to your .Rprofile. Several other good nuggets of programming happiness can be found hither on that topic.
I don't know of a native R function for doing this, but I know R has interfaces with other languages that do have system time commands. Maybe this is an option?
Thierry mentioned system.time() and there is also proc.time() depending on what you need it for, although neither of these give you the current time.

Making a TIME SERIES graph THAT SCROLLS WITH THE DATA in R

I need to do exactly the graph that has been made on this page (the second one)
http://www.animatedgraphs.co.uk/line.html
Here is my actual code :
timemax<-151737 # number of frames (and observations - so no interpolation needed)
setwd("C:/Users/victo/Downloads/ffmpeg/ffmpeg/bin/")
vis<-100 # how many time points are on the screen at one time
gdata<-data.frame('Temps'= data$time,'RH_Xacc'= data$RH_Xacc)
gname<-paste("g",1:timemax,".tif", sep="") # holds the names of the picture files
right<-(((1:timemax)<=vis)*100)+(((1:timemax)>vis)*1:timemax) # rightmost time on screen
left<- right-vis+2 # leftmost time on screen
leftlab<-200*ceiling((left-1)/200) # leftmost x label
rightlab<-200*floor(right/200) # rightmost x label
# draw graphs
for (i in 1:timemax) {
tiff(gname[i],width=480)
plot(gdata$Temps[right[i]:left[i]],gdata$RH_Xacc[right[i]:left[i]],col="red",type="l",ylim=c(-100,200),xlim=c(right[i],left[i]),xaxt="n",ylab="",xlab="time")
axis(1,at=seq(from=rightlab[i],to=leftlab[i],by=12))
lines(gdata$Temps[right[i]:i],gdata$RH_Xacc[right[i]:i])
dev.off(dev.cur())
}
# call FFMPEG and make the video
shell("C:/Users/victo/Downloads/ffmpeg/ffmpeg/bin/ffmpeg.exe -codecs -i g%d.tif -b:v 2048k gdata.mpg",mustWork=FALSE)
My code seems to work until the shell function. I don't get an error. The code just never stops running. I am not able to get the video with all the data. Can someone tell me where is the problem ? How can I get the video or if there is an other to get the same result ? I've tried the library gganimate but i didn't succeed either... I am doing this in Rstudio and using sweave.
Thanks a lot
Actually, the first thing you should do is probably run the command :
C:/Users/victo/Downloads/ffmpeg/ffmpeg/bin/ffmpeg.exe -codecs -i g%d.tif -b:v 2048k gdata.mpg directly and not with a calling shell from RStudio. You would have a more verbose output.
Original post
Do you have any CPU performance profiling tool ? I suspect that the shell command might take a lot of time to run on your computer since in your example : timemax<-151737 whereas the example has a shorter timemax timemax<-1000
Try your program with a low value of timemax (=1000) and time the execution of the code. I guess you could extrapolate the total time needed to execute multiplying by 150 (I am not an expert of ffmpeg, it might actually be longer)

Running R script_Readline and Scan does not pause for user input

I have looked at other posts that appeared similar to this question but they have not helped me. This may be just my ignorance of R. Thus I decided to sign up and make my first post on stack-overflow.
I am running an R-script and would like the user to decide either to use one of the two following loops. The code to decide user input looks similar to the one below:
#Define the function
method.choice<-function() {
Method.to.use<-readline("Please enter 'New' for new method and'Old' for old method: ")
while(Method.to.use!="New" && Method.to.use!="Old"){ #Make sure selection is one of two inputs
cat("You have not entered a valid input, try again", "\n")
Method.to.use<-readline("Please enter 'New' for new method and 'Old' for old method: ")
cat("You have selected", Method.to.use, "\n")
}
return(Method.to.use)
}
#Run the function
method.choice()
Then below this I have the two possible choices:
if(Method.to.use=="New") {
for(i in 1:nrow(linelist)){...}
}
if(Method.to.use=="Old"){
for(i in 1:nrow(linelist)){...}
}
My issue is, and what I have read from other posts, is that whether I use "readline", "scan" or "ask", R does not wait for my input. Instead R will use the following lines as the input.
The only way I found that R would pause for input is if the code is all on the same line or if it is run line by line (instead of selecting all the code at once). See example from gtools using "ask":
silly <- function()
{
age <- ask("How old are you? ")
age <- as.numeric(age)
cat("In 10 years you will be", age+10, "years old!\n")
}
This runs with a pause:
silly(); paste("this is quite silly")
This does not wait for input:
silly()
paste("this is quite silly")
Any guidance would be appreciated to ensure I can still run my entire script and have it pause at readline without continuing. I am using R-studio and I have checked that interactive==TRUE.
The only other work-around I found is wrapping my entire script into one main function, which is not ideal for me. This may require me to use <<- to write to my environment.
Thank you in advance.

Kill a calculation programme after user defined time in R

Say my executable is c:\my irectory\myfile.exe and my R script calls on this executeable with system(myfile.exe)
The R script gives parameters to the executable programme which uses them to do numerical calculations. From the ouput of the executable, the R script then tests whether the parameters are good ore not. If they are not good, the parameters are changed and the executable rerun with updated parameters.
Now, as this executable carries out mathematical calculations and solutions may converge only slowly I wish to be able to kill the executable once it has takes to long to carry out the calculations (say 5 seconds)
How do I do this time dependant kill?
PS:
My question is a little related to this one: (time non dependant kill)
how to run an executable file and then later kill or terminate the same process with R in Windows
You can add code to your R function which issued the executable call:
setTimeLimit(elapse=5, trans=T)
This will kill the calling function, returning control to the parent environment (which could well be a function as well). Then use the examples in the question you linked to for further work.
Alternatively, set up a loop which examines Sys.time and if the expected update to the parameter set has not taken place after 5 seconds, break the loop and issue the system kill command to terminate myfile.exe .
There might possibly be nicer ways but it is a solution.
The assumption here is, that myfile.exe successfully does its calculation within 5 seconds
try.wtl <- function(timeout = 5)
{
y <- evalWithTimeout(system(myfile.exe), timeout = timeout, onTimeout= "warning")
if(inherits(y, "try-error")) NA else y
}
case 1 (myfile.exe is closed after successfull calculation)
g <- try.wtl(5)
case 2 (myfile.exe is not closed after successfull calculation)
g <- try.wtl(0.1)
MSDOS taskkill required for case 2 to recommence from the beginnging
if (class(g) == "NULL") {system('taskkill /im "myfile.exe" /f',show.output.on.console = FALSE)}
PS: inspiration came from Time out an R command via something like try()

Programmatically close the window created by `View(x)`

I'm viewing a dataframe in R using View:
my_df <- data.frame(a=1:10, b=letters[1:10])
View(my_df)
I'd like to now close the resulting window programmatically (rather than clicking the X button).
How may I do this? graphics.off doesn't work as it isn't a graphics device. Looking at the View code, internal function dataviewer is used to display the window but I'm not sure what it uses in the background (tcltk?) so am not sure how to close the window.
Re some comments as to why I want this.
I'm basically doing a user-checking step in a script whereby the user is asked if a snippet of a dataframe and a corresponding image go together. It goes something like this:
for (i in 1:heaps) {
1. View(a snippet of a big dataframe)
2. show an image
3. readline('Is this OK? [Y/N]: ') (store the i for which it's not OK)
4. close the image window (graphics.off()), close the View(..) window.
}
I basically wanted to reduce the user interaction down staring at the image & dataframe snippet and typing Y or N, so they don't have to manually close th dataframe window for each i in the loop.
(I'm part-way through this validation myself and am dealing with 200 View(snippet) windows that I haven't bothered to close D:. Also, have noticed that the opening of the windows steals keyboard focus away from the prompt so me typing Y/N is not as fast as I'd like. But I only have to do this once, so it'll do for now. I am curious as to the answer to the question though, for next time).
One way to accomplish what you're after is to make use of the system function. You could, for example, determine the Window ID/Name and then issue a close command like so:
system('(sleep 10; wmctrl -c "Data: my_df") &')
The above command will wait 10 seconds, and then issue a command to the window manager to close any window with the name "Data: my_df". These 2 commands are wrapped in parens. This is known as a Compound Command in bash. The entire Compound Command is backgrounded, '&'.
I tested the following and it worked:
# sample1.R
my_df <- data.frame(a=1:10, b=letters[1:10])
system('(sleep 10; wmctrl -c "Data: my_df") &')
View(my_df)
Another way to accomplish this is like so:
# sample2.R
my_df <- data.frame(a=1:10, b=letters[1:10])
View(my_df)
system('read -p "Press [Enter] key to start backup..."')
my_df2 <- data.frame(a=1:10, b=letters[1:10])
View(my_df2)
system('read -p "Press [Enter] key to start backup..."')
I'm running these like this:
R CMD BATCH sample2.R
NOTE: The prompt from the read -p command isn't showing up in my terminal but you could just print a duplicate prompt message in R.
If you want to close all open "View" windows, building on the answer of slm :
CloseViews <- function(){
cmd <- paste0('wmctrl -c "Data:" -v')
ok <- TRUE
while(ok){
out <- suppressWarnings(system(cmd,intern=TRUE,ignore.stderr=TRUE))
Sys.sleep(0.2)
ok <- is.null(attr(out,"status"))
print(ok)
}
}
Then CloseViews() does the trick, which I found particularly helpful when working interactively.

Resources