Re: [R] Getting "Error in ect, plot.new has not been called yet" despite grouping plot call

2022-10-06 Thread Deramus, Thomas Patrick
Truly appreciate it Bill.

Will try to make something more trimmed down in the future, but unfortunately 
have to admit I am more of an R neophyte than I would like to be.

From: Joshua Ulrich 
Sent: Thursday, October 6, 2022 11:26 AM
To: Bill Dunlap 
Cc: Deramus, Thomas Patrick ; r-help@r-project.org 

Subject: Re: [R] Getting "Error in ect, plot.new has not been called yet" 
despite grouping plot call

External Email - Use Caution

On Thu, Oct 6, 2022 at 9:44 AM Bill Dunlap  wrote:
>
> Here is how you could have made an example that helpers could easily run.
> It also includes the fix.
>
> f <- function(print.it = FALSE) {
>pdf(file.pdf <- tempfile(fileext=".pdf"))
>series <- as.xts(setNames(sin(seq(0,10,by=.1)),
> seq(as.Date("2022-10-06"),by="weeks",len=101)))
>p <- plot(series)
>if (print.it) {
>print(p)
>}
>sm_series_2 <- smooth(series / 2)
>lines(sm_series_2, col="red")
>abline(h=0.1, col="blue")
>dev.off()
>file.pdf
> }
> > f()
> Error in plot.xy(xy.coords(x, y), type = type, ...) :
>   plot.new has not been called yet
> > f(TRUE)
> [1]
> "C:\\Users\\willi\\AppData\\Local\\Temp\\Rtmp0wX7rO\\file34843df652c.pdf"
>
> If you remove the pdf() and dev.off() I think you will see that the added
> lines do not show up.  I think plot.xts fiddles with the coordinate system
> before and after it plots so that add-ons must be done in a special way.
>

plot.xts() waits until the plot is rendered before calculating the
coordinate system. That allows users to add multiple series that have
different values for the index (x-axis) and data (y-axis).

lines() doesn't show up in your example because it's called after the
plot is rendered, and it's not rendered again after they're added.
`sm_series_2` also needs to be an xts object, otherwise lines.xts() is
not dispatched.

title() and abline() need to be called after the plot is rendered
because they are standard graphics functions. I admit that's very
confusing... I'll see what I can do to fix that.

Here's a revised example that works for me:

f <- function(print.it = FALSE)
{
pdf(file.pdf <- tempfile(fileext=".pdf"))
series <- xts(sin(seq(0,10,by=.1)),
seq(as.Date("2022-10-06"),by="weeks",length.out=101))
p <- plot(series)
sm2 <- xts(smooth(series/2), index(series))
lines(sm2, col="red")
if (print.it) {
print(p)
title("Sine curve example")
abline(h=0.1, col="green")
}
dev.off()
file.pdf
}
f(TRUE)



> -Bill
>
> On Thu, Oct 6, 2022 at 12:42 AM Deramus, Thomas Patrick <
> tdera...@partners.org> wrote:
>
> > Hi Rolf.
> >
> > I followed your suggestion (though it's probably not as trimmed as it
> > could be), but the problem unfortunately persists.
> >
> > Does this make it any clearer or still too many moving parts to make sense
> > of?
> >
> > rm(list = ls(all.names = TRUE)) #will clear all objects includes hidden
> > objects.
> >
> > #Loads the packages
> > library(plyr)
> > library(dplyr)
> > library(ggplot2)
> > library(Kendall)
> > library(lubridate)
> > library(xts)
> > library(TTR)
> > library(trend)
> > library(forecast)
> > library(openxlsx)
> >
> > #Uses the learningCurve Package from Github:
> > #https://secure-web.cisco.com/1GC2a24rvTQn4ZsRD2yEzdiU8p0VcreF81tS2HTnyYa7VJF5IpO2yI1E7CRvAjkTDIaj6KEYqjTGRSAenLfIdC6jV3OEUiCZS17V58pTwQ-55guIdhru6Sek8uJuW1ts44qoo8ZbniSWEwzzch1DcQTxCe9raR3xZavXdeOins1Yzg7le2LJWuRBEk8s9CxpKUsKa9l3qmWmjRszIWVX7nZSBTjnNOFTcJgqc8MQu8qZojb4GwCZ8mlP7U4dQdClXlDxxlTL6kF-Awi1NmycuaWn8MYEjxDTpdyqw97MAkHjESJbjB7Hfv93No-E5_9cp/https%3A%2F%2Fgithub.com%2FAFIT-R%2FlearningCurve
> > library(learningCurve)
> >
> > #Only load this if using VS Studio because it changes the plot function
> > #
> > https://secure-web.cisco.com/19uRRA2OdQiP-LFePtct8U8sQ1opEP7PrOFLjX3GDTAREApng8FFteGdDY-n8lnkoclvIekYRw4YgvqG24Tsovdeq3hKnKx6iBpWoAy-tOijBFwH0AKBvugicSxwCStU9yZANYx2BTYDd8bYZoEkwTYnthGTH4AKLybu5ek_wJMX0hCEzx9IxjRZ-03ISDvocEUUspf4uxi841j1qW7mAZ3WMj4pjTUa8mlUznIxtkTeEdGYN0X4j3Q5iiwLin6l0gntobwjoaTMv_0kq8hQe6_cYJCxBVxU-CEYcY8KPjsM9YBC-oYeFhUt13Wqlj-mO/https%3A%2F%2Fstackoverflow.com%2Fquestions%2F52284345%2Fhow-to-show-r-graph-from-visual-studio-code
> > library(httpgd)
> > library(languageserver)
> >
> > #Loads the Excel files to Dataframes and cleans the data
> > Game_Metrics_Word_Task <-
> > read.xlsx("GamePack_Analytics_ALL_TIME_Short.xlsx", "Boggle")
> > Game_Metrics_Word_Task <

Re: [R] Getting "Error in ect, plot.new has not been called yet" despite grouping plot call

2022-10-06 Thread Joshua Ulrich
> > c(0))
> >
> > #The number of subjects in the xlsx file
> > #Reduced to 2 for ease of use
> > for (i in 1:2){
> >   #This timeseries only includes the trials where the participant
> > completed the task
> >   success_series <- xts(filter(Participant_Word_Task[[i]], GameEndReason
> > == "TIMER_UP")$NumberOfSuccesfulWords , 
> > order.by=as.POSIXct(filter(Participant_Word_Task[[i]],
> > GameEndReason == "TIMER_UP")$DeviceTime))
> >   #This timeseries includes ALL the trials for the sake of plotting
> >   original_series <-
> > xts(Participant_Word_Task[[i]]$NumberOfSuccesfulWords, order.by
> > =as.POSIXct(Participant_Word_Task[[i]]$DeviceTime))
> >
> >   #This is a decomposing process that xts seems to need for plotting.
> >   #nweeks is needed for xts to plot the x-axis
> >   success_decomp <- ts(success_series, frequency = nweeks(success_series))
> >   original_decomp <- ts(original_series, frequency =
> > nweeks(success_series))
> >
> >   #Values which will be included in the plots
> >   WordFrame[i,1] <- unique(Participant_Word_Task[[i]]$StudyId)
> >   WordFrame[i,5] <- sens.slope(success_decomp)$estimates
> >   WordFrame[i,6] <- sens.slope(success_decomp)$p.value
> >   WordFrame[i,7] <- pettitt.test(success_decomp)$estimate
> >   WordFrame[i,8] <- pettitt.test(success_decomp)$p.value
> >
> >   #The simple moving average that will be overlayed with the plotted data
> >   simplemovingaverage <- SMA(original_series, n = nweeks(original_series))
> >
> >   #If the three tests are statistically significant, add a green
> > horizontal like to value WordFrame[i,7]
> >   #Which would be where the slope changes in the series
> >   #Fluid variables have been removed from all pdf() and paste() functions
> > for ease-of-use
> >   if (WordFrame[i,4] <= 0.05 & WordFrame[i,6] <= 0.05 & WordFrame[i,8] <=
> > 0.05){
> >  {
> >   pdf(file = "Word_Task_Acquisition.pdf")
> >   plout <- plot(original_series)
> >   lines(simplemovingaverage)
> >   abline(v = index(original_series[WordFrame[i,7]]),lty=2,
> > col='green', lwd=3)
> >   title(paste("Word Task Acquisition for Subject"))
> >   dev.off()
> >  }
> >   #If the three tests are NOT statistically significant, generate a plot
> > with NO horizontal line at WordFrame[i,7]
> >   } else {
> > {
> >   pdf(file = "Word_Task_Acquisition.pdf")
> >   plout <- plot(original_series)
> >   lines(simplemovingaverage)
> >   title(paste("Word Task Acquisition for Subject"))
> >   dev.off()
> > }
> >   }
> > }
> >
> > 
> > From: Rolf Turner 
> > Sent: Wednesday, October 5, 2022 6:06 AM
> > To: Deramus, Thomas Patrick 
> > Cc: r-help@r-project.org 
> > Subject: Re: [R] Getting "Error in ect, plot.new has not been called yet"
> > despite grouping plot call
> >
> > External Email - Use Caution
> >
> > What you doing or trying to do is far too complex for my poor feeble
> > and senile brain to come anywhere near comprehending.  The code that
> > you present exceeds my complexity tolerance by many orders of magnitude.
> >
> > I have a suggestion, but.  Strip your code down to the *essentials*.
> > Construct a simple sequence of plotting commands, with *simple* names
> > for the pdf files involved.  You should require only two or three such
> > files and two or three index levels associated with each of your
> > nested loops.
> >
> > Run the stripped down code and the source of the problem will almost
> > surely become clear.
> >
> > cheers,
> >
> > Rolf Turner
> >
> > On Tue, 4 Oct 2022 23:35:09 +
> > "Deramus, Thomas Patrick"  wrote:
> >

> > > —Issac Asimov
> >
> > The information in this e-mail is intended only for th...{{dropped:22}}
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



-- 
Joshua Ulrich  |  about.me/joshuaulrich
FOSS Trading  |  www.fosstrading.com

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Getting "Error in ect, plot.new has not been called yet" despite grouping plot call

2022-10-06 Thread Bill Dunlap
i,7]
>   #Which would be where the slope changes in the series
>   #Fluid variables have been removed from all pdf() and paste() functions
> for ease-of-use
>   if (WordFrame[i,4] <= 0.05 & WordFrame[i,6] <= 0.05 & WordFrame[i,8] <=
> 0.05){
>  {
>   pdf(file = "Word_Task_Acquisition.pdf")
>   plout <- plot(original_series)
>   lines(simplemovingaverage)
>   abline(v = index(original_series[WordFrame[i,7]]),lty=2,
> col='green', lwd=3)
>   title(paste("Word Task Acquisition for Subject"))
>   dev.off()
>      }
>   #If the three tests are NOT statistically significant, generate a plot
> with NO horizontal line at WordFrame[i,7]
>   } else {
> {
>   pdf(file = "Word_Task_Acquisition.pdf")
>   plout <- plot(original_series)
>   lines(simplemovingaverage)
>   title(paste("Word Task Acquisition for Subject"))
>   dev.off()
> }
>   }
> }
>
> 
> From: Rolf Turner 
> Sent: Wednesday, October 5, 2022 6:06 AM
> To: Deramus, Thomas Patrick 
> Cc: r-help@r-project.org 
> Subject: Re: [R] Getting "Error in ect, plot.new has not been called yet"
> despite grouping plot call
>
> External Email - Use Caution
>
> What you doing or trying to do is far too complex for my poor feeble
> and senile brain to come anywhere near comprehending.  The code that
> you present exceeds my complexity tolerance by many orders of magnitude.
>
> I have a suggestion, but.  Strip your code down to the *essentials*.
> Construct a simple sequence of plotting commands, with *simple* names
> for the pdf files involved.  You should require only two or three such
> files and two or three index levels associated with each of your
> nested loops.
>
> Run the stripped down code and the source of the problem will almost
> surely become clear.
>
> cheers,
>
> Rolf Turner
>
> On Tue, 4 Oct 2022 23:35:09 +
> "Deramus, Thomas Patrick"  wrote:
>
> > Sorry to cross-post on Stackoverflow and here but I'm having some
> > difficulty.
> >
> https://secure-web.cisco.com/1_juqv4RvefQFJofsnOQcQA3Ixge89s4uC26pjoPBaYOSxSLGisKtgUTZkanxeHNRqNmjl30B8wYKfsppHje4T8Su77i7t8UbMKzs3GBKEyQva4yTjPH76Q9-l6tT24bB4qNMPQeFAxrkG5lpozNpGrDIAjfKCMvgS-5Qjs-QmvhWZfo84_3SK9rHhJjJvO9CqXb0MewWwI-dEmkZemjxnliGe_D9nooo7Ebjuw0dpBuMnrdaTzQxDdivsbkujPnrGurdjLARh93RW5IWPszNwaoziRD7P-30McF1PrAP8_yjWrhxQ_S3AgG6k40EoQJU/https%3A%2F%2Fstackoverflow.com%2Fquestions%2F73942794%2Fstill-getting-error-in-ect-plot-new-has-not-been-called-yet-despite-grouping
> >
> > Trying to make a nested loop that produces PDFs off different graphs,
> > one for ACF/PACF diagnostics and another for the actual data, based
> > on some time-series analyses I'm doing.
> >
> > Unfortunately, I keep getting the dreaded: Error plot.new has not
> > been called yet
> >
> > The code is meant to write a PDF containing the ACF and PACF graphs,
> > then do some analyses on the timeseries, and then make a separate PDF
> > containing a plot describing the timeseries based on the p-values of
> > each test for each individual.
> >
> > library(plyr)
> > library(dplyr)
> > library(ggplot2)
> > library(Kendall)
> > library(lubridate)
> > library(xts)
> > library(TTR)
> > library(trend)
> > library(forecast)
> > library(openxlsx)
> >
> > Game_Metrics_Word_Task <-
> > read.xlsx("GamePack_Analytics_ALL_TIME_Short.xlsx", "Boggle")
> > Game_Metrics_Word_Task <- Game_Metrics_Word_Task %>%
> > filter(grepl('1440', StudyId)) Game_Metrics_Word_Task$DeviceTime <-
> > ymd_hms(Game_Metrics_Word_Task$DeviceTime,  tz = "America/New_York")
> > Game_Metrics_Word_Task <-
> > Game_Metrics_Word_Task[!duplicated(Game_Metrics_Word_Task[1:2,])]
> >
> > Participant_Word_Task <-
> > split(arrange(Game_Metrics_Word_Task,StudyId,DeviceTime),
> >
> arrange(Game_Metrics_Word_Task,StudyId,DeviceTime,StudyId,DeviceTime)$StudyId)
> >
> > WordFrame <- data.frame(Participant = c(0), Task = c(0),
> > MannKendall_Tau = c(0), MannKendall_P = c(0), Sen_Slope_Value = c(0),
> > Sen_Slope_Pval = c(0), Pettitts_CIV = c(0), Pettitts_Pval = c(0),
> > ARIMA_Model = c(0), Time_to_Petit = c(0), Number_of_Trials_to_Pettitt
> > = c(0), Playtime_to_Petit_seconds = c(0), Time_Start_to_end_days =
> > c(0), Number_of_Total_Trials = c(0), Total_Playtime_seconds = c(0),
> > Learning_rate_days = c(0), Learning_rate_seconds = c(0), Learned_Task
> > = c(0))
> >
> > for (i in 1:length(Participant_Word

Re: [R] Getting "Error in ect, plot.new has not been called yet" despite grouping plot call

2022-10-06 Thread Deramus, Thomas Patrick
I had to place it right before the title and abline functions like so:

for (i in 1:length(Participant_Word_Task)){
success_series <- xts(filter(Participant_Word_Task[[i]], GameEndReason == 
"TIMER_UP")$NumberOfSuccesfulWords , 
order.by=as.POSIXct(filter(Participant_Word_Task[[i]], GameEndReason == 
"TIMER_UP")$DeviceTime))
original_series <- xts(Participant_Word_Task[[i]]$NumberOfSuccesfulWords, 
order.by=as.POSIXct(Participant_Word_Task[[i]]$DeviceTime))
success_decomp <- ts(success_series, frequency = nweeks(success_series))
original_decomp <- ts(original_series, frequency = nweeks(success_series))
WordFrame[i,1] <- unique(Participant_Word_Task[[i]]$StudyId)
WordFrame[i,2] <- "Boggle"
WordFrame[i,3] <- MannKendall(success_decomp)$tau[1]
WordFrame[i,4] <- MannKendall(success_decomp)$sl[1]
WordFrame[i,5] <- sens.slope(success_decomp)$estimates
WordFrame[i,6] <- sens.slope(success_decomp)$p.value
WordFrame[i,7] <- pettitt.test(success_decomp)$estimate
WordFrame[i,8] <- pettitt.test(success_decomp)$p.value
WordFrame[i,10] <- 
difftime(time(success_series[WordFrame[i,7]]),time(original_series[1]))
WordFrame[i,11] <- tail(which(grepl(success_series[WordFrame[i,7]], 
original_series)), n=1)
WordFrame[i,12] <- 
sum(Participant_Word_Task[[i]]$TotalDuration[1:WordFrame[i,11]])-sum(Participant_Word_Task[[i]]$TotalTimePaused[1:WordFrame[i,11]])
WordFrame[i,13] <- 
difftime(time(original_series[length(original_series)]),time(original_series[1]))
WordFrame[i,14] <- length(original_series)
WordFrame[i,15] <- 
sum(Participant_Word_Task[[i]]$TotalDuration[1:length(original_series)])-sum(Participant_Word_Task[[i]]$TotalTimePaused[1:length(original_series)])


simplemovingaverage <- SMA(original_series, n = nweeks(original_series))
if (WordFrame[i,4] <= 0.05 & WordFrame[i,6] <= 0.05 & WordFrame[i,8] <= 
0.05){

 lines(simplemovingaverage,type='l',col='red'); title(paste("Word Task 
Acquisition for Subject", WordFrame[i,1])); abline(v = 
index(original_series[WordFrame[i,7]]),lty=2, col='green', lwd=3); dev.off()
  {
  pdf(file = paste(WordFrame[i,1],"_Word_Task_Acquisition.pdf",collapse = 
NULL, sep = ""))
  plout <- plot(original_series,type='l',col='blue',xlab="Date of 
Play",ylab="Number of Successful Words")
  lines(simplemovingaverage,type='l',col='red')
  print(plout)
  title(paste("Word Task Acquisition for Subject", WordFrame[i,1]))
  abline(v = index(original_series[WordFrame[i,7]]),lty=2, col='green', 
lwd=3)
  dev.off()
  }

  WordFrame[i,18] <- T
  WordFrame[i,16] <- (1-(WordFrame[i,10]/WordFrame[i,13]))
  WordFrame[i,17] <- (1-(WordFrame[i,12]/WordFrame[i,15]))
} else {
  {
  pdf(file = paste(WordFrame[i,1],"_Word_Task_Acquisition.pdf",collapse = 
NULL, sep = ""))
  plout <- plot(original_series,type='l',col='blue',xlab="Date of 
Play",ylab="Number of Successful Words")
  lines(simplemovingaverage,type='l',col='red')
  print(plout)
  title(paste("Word Task Acquisition for Subject", WordFrame[i,1]))
  dev.off()
  }

  WordFrame[i,18] <- F
  WordFrame[i,16] <- 0
  WordFrame[i,17] <- 0
    }
}
​
But as soon as I did that it worked!

Thank you so much!

From: Joshua Ulrich 
Sent: Wednesday, October 5, 2022 9:16 PM
To: Deramus, Thomas Patrick 
Cc: R-Help 
Subject: Re: [R] Getting "Error in ect, plot.new has not been called yet" 
despite grouping plot call


External Email - Use Caution

Hi,

My hunch is that you need to add print(plout) before you call dev.off(). See 
https://stackoverflow.com/a/39853861<https://secure-web.cisco.com/1hPT2Maoird0h5FIvJrkRlN2QFkkujjs4YnHgtB5wYLuhRcHZGZ5SmvPC6x4VQ-rT2HqRBreJ_YeWM8Ug8HtScdp7g_E7nS4BfkHFtjiAKRId_AjYMKIvoJa-YojoOECa97gbnLx2QU535CBNKtd0Z-dzQns8z-C4Du8Jh6K3rEvmlP25DscJvrNcRUbisHQ67um6b6a-H9bqYYN-7QtBp2OGBjnh4LBzDR3TnMNVEF0dbhYTuP5zgP2NsHtCvRrwRUUApS1ZqUT0iiiQCrto3zWrSVlQ6aVOqTBgneUBEk_-8SkwVLgOccgGZyw37JTo/https%3A%2F%2Fstackoverflow.com%2Fa%2F39853861>

Try that and let me know if that works. If not, I'll take a closer look later.

Best,
Josh


On Wed, Oct 5, 2022, 1:40 AM Deramus, Thomas Patrick 
mailto:tdera...@partners.org>> wrote:
Sorry to cross-post on Stackoverflow and here but I'm having some difficulty.
https://stackoverflow.com/questions/73942794/still-getting-error-in-ect-plot-new-has-not-been-called-yet-despite-grouping<https://secure-web.cisco.com/1Xaq1EClv5yIy5MQnXyJBRP44YCvR9TkouPyPXmenkL1IktK5tDxQ_MynVlVIbnlxMlCViUOwZZPfM6GNcEI1NlAqV7y-6RhsR6Qy1m90ENv5mp19zbOX-f-IqNkbFHuGZZLCBFkq0sMS_waWZZSj3Su0bNo5Y1b3zCkVoVLl1Go2J2A1jWX3fvSvOP2ArzpHWt9qX8HZpoGVkadBfUmANamoUw5ucuBsXvvaWdl1skYiJzSVy

Re: [R] Getting "Error in ect, plot.new has not been called yet" despite grouping plot call

2022-10-06 Thread Deramus, Thomas Patrick
Odd. Thought I had attached it.

Would love to go that route, but the problem is a lot of the sub-bits are 
actually dependent on the values of the timeseries analysis, which has its own 
dependencies..

Would using the following link to download the excel file help at all?
https://docs.google.com/spreadsheets/d/1rPd8bv4WADCdEUhmem-u1-6HWUXKne7b/edit?usp=sharing=110307531005009211602=true=true



From: Rolf Turner 
Sent: Wednesday, October 5, 2022 6:28 PM
To: Deramus, Thomas Patrick 
Cc: r-help@r-project.org 
Subject: Re: [R] Getting "Error in ect, plot.new has not been called yet" 
despite grouping plot call

External Email - Use Caution


Your code is still much too complex for my feeble brain.

Without trying to understand very much, I get the impression that the
example is *not* reproducible.  It requires reading in Excel (yeucchh!)
files to which no-one but you has access.

Skip the reading-in completely.  Create toy data using rnorm() instead.
Then someone may be able to help you.

On Wed, 5 Oct 2022 13:32:00 +
"Deramus, Thomas Patrick"  wrote:

> Hi Rolf.
>
> I followed your suggestion (though it's probably not as trimmed as it
> could be), but the problem unfortunately persists.

If the problem *didn't* persist, then *that* would have been
unfortunate!  The idea is to reproduce the problem in a simpler context
so that one can deduce what is causing the problem!

> Does this make it any clearer or still too many moving parts to make
> sense of?

There are still (far) too many moving parts, for me anyway.  Someone
cleverer than I might be able to see what the problem is.

cheers,

Rolf

>
> rm(list = ls(all.names = TRUE)) #will clear all objects includes
> hidden objects.
>
> #Loads the packages
> library(plyr)
> library(dplyr)
> library(ggplot2)
> library(Kendall)
> library(lubridate)
> library(xts)
> library(TTR)
> library(trend)
> library(forecast)
> library(openxlsx)
>
> #Uses the learningCurve Package from Github:
> #https://secure-web.cisco.com/1GUXNs4DRqUHykKAjZUB89_m2M_KU7oUJ6jl9VAWbtn8YCzSy8qRCHe-LJf3ovhQXKpQcXQe9Bf_BwKHFn4-A8AvtoD_tuXR-jsEcSsEQp-B3sET59hXmBKs_B1M7u2zUxnGNqVZnxYNeip71STXGupngENp0IjZfxd48SZHkztp5CLHFpsdHgz7wHHwePlSTMG8yKmYcS7N6OSkoxENvsL-vCxACXlyPFQTynaQNNjFjV7Ngl8mJpBP0G8pXX8WbogbQlE9ArbYCph6j_3IoVIN8Y6dKqRe44yoi8S3hjJ1PFgdr4JW7nve07XYaC_M-/https%3A%2F%2Fgithub.com%2FAFIT-R%2FlearningCurve
> library(learningCurve)
>
> #Only load this if using VS Studio because it changes the plot
> function
> #https://secure-web.cisco.com/14TdkUQ3Ymy411VwAMhagZmvgDM4nborDvLmLccRSdK1n3ZgXfjjdH9Xn1dVxO2s5Y9R4fZJoitgys453O-kPVFt73W5s3Qa_D078MPMxoTGV6UP55ozAuPwt9nzMGBqak6abbcX1Er2q8CwEMGQJA8AmcdQf0GyGCz8b1qYV-ck9_L4N-Yq5eTWLs2NHrklR0XpUzWvbUBGRH2LpeWPHRLtMZjW8-9T3_1sGyvCHTXDhQ-FXzifBiFtE13_qL50iO1kl8A6p3EeOR0e0-AgW-kGEfpBHGgA53VBlscnA9nqfb60sCgLaAeMz-Pc49ITI/https%3A%2F%2Fstackoverflow.com%2Fquestions%2F52284345%2Fhow-to-show-r-graph-from-visual-studio-code
> library(httpgd) library(languageserver)
>
> #Loads the Excel files to Dataframes and cleans the data
> Game_Metrics_Word_Task <-
> read.xlsx("GamePack_Analytics_ALL_TIME_Short.xlsx", "Boggle")
> Game_Metrics_Word_Task <- Game_Metrics_Word_Task %>%
> filter(grepl('1440', StudyId)) Game_Metrics_Word_Task$DeviceTime <-
> ymd_hms(Game_Metrics_Word_Task$DeviceTime,  tz = "America/New_York")
> Game_Metrics_Word_Task <-
> Game_Metrics_Word_Task[!duplicated(Game_Metrics_Word_Task[1:2,])]
>
> #Splits the dataframe into a tibble containing each participant
> Participant_Word_Task <-
> split(arrange(Game_Metrics_Word_Task,StudyId,DeviceTime),
> arrange(Game_Metrics_Word_Task,StudyId,DeviceTime,StudyId,DeviceTime)$StudyId)
>
> #Generates a blank output dataframe
> WordFrame <- data.frame(Participant = c(0), Task = c(0),
> MannKendall_Tau = c(0), MannKendall_P = c(0), Sen_Slope_Value = c(0),
> Sen_Slope_Pval = c(0), Pettitts_CIV = c(0), Pettitts_Pval = c(0),
> ARIMA_Model = c(0), Time_to_Petit = c(0), Number_of_Trials_to_Pettitt
> = c(0), Playtime_to_Petit_seconds = c(0), Time_Start_to_end_days =
> c(0), Number_of_Total_Trials = c(0), Total_Playtime_seconds = c(0),
> Learning_rate_days = c(0), Learning_rate_seconds = c(0), Learned_Task
> = c(0))
>
> #The number of subjects in the xlsx file
> #Reduced to 2 for ease of use
> for (i in 1:2){
>   #This timeseries only includes the trials where the participant
> completed the task success_series <-
> xts(filter(Participant_Word_Task[[i]], GameEndReason ==
> "TIMER_UP")$NumberOfSuccesfulWords ,
> order.by=as.POSIXct(filter(Participant_Word_Task[[i]], GameEndReason
> == "TIMER_UP")$DeviceTime)) #This timeseries includes ALL the trials
> for the sake of plotting original_se

Re: [R] Getting "Error in ect, plot.new has not been called yet" despite grouping plot call

2022-10-06 Thread Deramus, Thomas Patrick
Hi Rolf.

I followed your suggestion (though it's probably not as trimmed as it could 
be), but the problem unfortunately persists.

Does this make it any clearer or still too many moving parts to make sense of?

rm(list = ls(all.names = TRUE)) #will clear all objects includes hidden objects.

#Loads the packages
library(plyr)
library(dplyr)
library(ggplot2)
library(Kendall)
library(lubridate)
library(xts)
library(TTR)
library(trend)
library(forecast)
library(openxlsx)

#Uses the learningCurve Package from Github:
#https://github.com/AFIT-R/learningCurve
library(learningCurve)

#Only load this if using VS Studio because it changes the plot function
#https://stackoverflow.com/questions/52284345/how-to-show-r-graph-from-visual-studio-code
library(httpgd)
library(languageserver)

#Loads the Excel files to Dataframes and cleans the data
Game_Metrics_Word_Task <- read.xlsx("GamePack_Analytics_ALL_TIME_Short.xlsx", 
"Boggle")
Game_Metrics_Word_Task <- Game_Metrics_Word_Task %>% filter(grepl('1440', 
StudyId))
Game_Metrics_Word_Task$DeviceTime <- ymd_hms(Game_Metrics_Word_Task$DeviceTime, 
 tz = "America/New_York")
Game_Metrics_Word_Task <- 
Game_Metrics_Word_Task[!duplicated(Game_Metrics_Word_Task[1:2,])]

#Splits the dataframe into a tibble containing each participant
Participant_Word_Task <- 
split(arrange(Game_Metrics_Word_Task,StudyId,DeviceTime), 
arrange(Game_Metrics_Word_Task,StudyId,DeviceTime,StudyId,DeviceTime)$StudyId)

#Generates a blank output dataframe
WordFrame <- data.frame(Participant = c(0), Task = c(0), MannKendall_Tau = 
c(0), MannKendall_P = c(0), Sen_Slope_Value = c(0), Sen_Slope_Pval = c(0), 
Pettitts_CIV = c(0), Pettitts_Pval = c(0), ARIMA_Model = c(0), Time_to_Petit = 
c(0), Number_of_Trials_to_Pettitt = c(0), Playtime_to_Petit_seconds = c(0), 
Time_Start_to_end_days = c(0), Number_of_Total_Trials = c(0), 
Total_Playtime_seconds = c(0), Learning_rate_days = c(0), Learning_rate_seconds 
= c(0), Learned_Task = c(0))

#The number of subjects in the xlsx file
#Reduced to 2 for ease of use
for (i in 1:2){
  #This timeseries only includes the trials where the participant completed the 
task
  success_series <- xts(filter(Participant_Word_Task[[i]], GameEndReason == 
"TIMER_UP")$NumberOfSuccesfulWords , 
order.by=as.POSIXct(filter(Participant_Word_Task[[i]], GameEndReason == 
"TIMER_UP")$DeviceTime))
  #This timeseries includes ALL the trials for the sake of plotting
  original_series <- xts(Participant_Word_Task[[i]]$NumberOfSuccesfulWords, 
order.by=as.POSIXct(Participant_Word_Task[[i]]$DeviceTime))

  #This is a decomposing process that xts seems to need for plotting.
  #nweeks is needed for xts to plot the x-axis
  success_decomp <- ts(success_series, frequency = nweeks(success_series))
  original_decomp <- ts(original_series, frequency = nweeks(success_series))

  #Values which will be included in the plots
  WordFrame[i,1] <- unique(Participant_Word_Task[[i]]$StudyId)
  WordFrame[i,5] <- sens.slope(success_decomp)$estimates
  WordFrame[i,6] <- sens.slope(success_decomp)$p.value
  WordFrame[i,7] <- pettitt.test(success_decomp)$estimate
  WordFrame[i,8] <- pettitt.test(success_decomp)$p.value

  #The simple moving average that will be overlayed with the plotted data
  simplemovingaverage <- SMA(original_series, n = nweeks(original_series))

  #If the three tests are statistically significant, add a green horizontal 
like to value WordFrame[i,7]
  #Which would be where the slope changes in the series
  #Fluid variables have been removed from all pdf() and paste() functions for 
ease-of-use
  if (WordFrame[i,4] <= 0.05 & WordFrame[i,6] <= 0.05 & WordFrame[i,8] <= 0.05){
 {
  pdf(file = "Word_Task_Acquisition.pdf")
  plout <- plot(original_series)
  lines(simplemovingaverage)
  abline(v = index(original_series[WordFrame[i,7]]),lty=2, col='green', 
lwd=3)
  title(paste("Word Task Acquisition for Subject"))
  dev.off()
 }
  #If the three tests are NOT statistically significant, generate a plot with 
NO horizontal line at WordFrame[i,7]
  } else {
{
  pdf(file = "Word_Task_Acquisition.pdf")
  plout <- plot(original_series)
  lines(simplemovingaverage)
  title(paste("Word Task Acquisition for Subject"))
  dev.off()
}
  }
}

____________
From: Rolf Turner 
Sent: Wednesday, October 5, 2022 6:06 AM
To: Deramus, Thomas Patrick 
Cc: r-help@r-project.org 
Subject: Re: [R] Getting "Error in ect, plot.new has not been called yet" 
despite grouping plot call

External Email - Use Caution

What you doing or trying to do is far too complex for my poor feeble
and senile brain to come anywhere near comprehending.  The code that
you present exceeds my complexity tolerance by many orders of magnitude.

I have a suggestion, but.  Strip your code down t

Re: [R] Getting "Error in ect, plot.new has not been called yet" despite grouping plot call

2022-10-05 Thread Joshua Ulrich
Hi,

My hunch is that you need to add print(plout) before you call dev.off().
See https://stackoverflow.com/a/39853861

Try that and let me know if that works. If not, I'll take a closer look
later.

Best,
Josh


On Wed, Oct 5, 2022, 1:40 AM Deramus, Thomas Patrick 
wrote:

> Sorry to cross-post on Stackoverflow and here but I'm having some
> difficulty.
>
> https://stackoverflow.com/questions/73942794/still-getting-error-in-ect-plot-new-has-not-been-called-yet-despite-grouping
>
> Trying to make a nested loop that produces PDFs off different graphs, one
> for ACF/PACF diagnostics and another for the actual data, based on some
> time-series analyses I'm doing.
>
> Unfortunately, I keep getting the dreaded: Error plot.new has not been
> called yet
>
> The code is meant to write a PDF containing the ACF and PACF graphs, then
> do some analyses on the timeseries, and then make a separate PDF containing
> a plot describing the timeseries based on the p-values of each test for
> each individual.
>
> library(plyr)
> library(dplyr)
> library(ggplot2)
> library(Kendall)
> library(lubridate)
> library(xts)
> library(TTR)
> library(trend)
> library(forecast)
> library(openxlsx)
>
> Game_Metrics_Word_Task <-
> read.xlsx("GamePack_Analytics_ALL_TIME_Short.xlsx", "Boggle")
> Game_Metrics_Word_Task <- Game_Metrics_Word_Task %>% filter(grepl('1440',
> StudyId))
> Game_Metrics_Word_Task$DeviceTime <-
> ymd_hms(Game_Metrics_Word_Task$DeviceTime,  tz = "America/New_York")
> Game_Metrics_Word_Task <-
> Game_Metrics_Word_Task[!duplicated(Game_Metrics_Word_Task[1:2,])]
>
> Participant_Word_Task <-
> split(arrange(Game_Metrics_Word_Task,StudyId,DeviceTime),
> arrange(Game_Metrics_Word_Task,StudyId,DeviceTime,StudyId,DeviceTime)$StudyId)
>
> WordFrame <- data.frame(Participant = c(0), Task = c(0), MannKendall_Tau =
> c(0), MannKendall_P = c(0), Sen_Slope_Value = c(0), Sen_Slope_Pval = c(0),
> Pettitts_CIV = c(0), Pettitts_Pval = c(0), ARIMA_Model = c(0),
> Time_to_Petit = c(0), Number_of_Trials_to_Pettitt = c(0),
> Playtime_to_Petit_seconds = c(0), Time_Start_to_end_days = c(0),
> Number_of_Total_Trials = c(0), Total_Playtime_seconds = c(0),
> Learning_rate_days = c(0), Learning_rate_seconds = c(0), Learned_Task =
> c(0))
>
> for (i in 1:length(Participant_Word_Task)){
> success_series <- xts(filter(Participant_Word_Task[[i]], GameEndReason
> == "TIMER_UP")$NumberOfSuccesfulWords , 
> order.by=as.POSIXct(filter(Participant_Word_Task[[i]],
> GameEndReason == "TIMER_UP")$DeviceTime))
> original_series <-
> xts(Participant_Word_Task[[i]]$NumberOfSuccesfulWords, order.by
> =as.POSIXct(Participant_Word_Task[[i]]$DeviceTime))
> success_decomp <- ts(success_series, frequency =
> nweeks(success_series))
> original_decomp <- ts(original_series, frequency =
> nweeks(success_series))
>
>
> pdf(paste("Word_Task_Autocorrelation_plots_for_subject_",unique(Participant_Word_Task[[i]]$StudyId),".pdf"
> ,collapse = NULL, sep = ""))
> par(mfrow=c(1,2))
> Autocorrelationplot <- acf(success_decomp, main=paste(""))
> PartialAutocorrelationplot <- pacf(success_decomp, main=paste(""))
> mtext(paste("Word Task Auto and Partialauto correlations for subject
> ",unique(Participant_Word_Task[[i]]$StudyId)), side = 3, line = -3, outer =
> TRUE)
> dev.off()
>
> AutomatedArimaoutputs <- auto.arima(success_decomp)
> p <- length(AutomatedArimaoutputs$model$phi)
> #AR component
> q <- length(AutomatedArimaoutputs$model$theta)
> #MA component
> d <- AutomatedArimaoutputs$model$Delta
> #order of difference
> WordFrame[i,1] <- unique(Participant_Word_Task[[i]]$StudyId)
> WordFrame[i,2] <- "Word"
> WordFrame[i,3] <- MannKendall(success_decomp)$tau[1]
> WordFrame[i,4] <- MannKendall(success_decomp)$sl[1]
> WordFrame[i,5] <- sens.slope(success_decomp)$estimates
> WordFrame[i,6] <- sens.slope(success_decomp)$p.value
> WordFrame[i,7] <- pettitt.test(success_decomp)$estimate
> WordFrame[i,8] <- pettitt.test(success_decomp)$p.value
> WordFrame[i,9] <- paste("ARIMA(",p,",",q,",",d,")", collapse = NULL,
> sep = "")
> WordFrame[i,10] <-
> difftime(time(success_series[WordFrame[i,7]]),time(original_series[1]))
> WordFrame[i,11] <- tail(which(grepl(success_series[WordFrame[i,7]],
> original_series)), n=1)
> WordFrame[i,12] <-
> sum(Participant_Word_Task[[i]]$TotalDuration[1:WordFrame[i,11]])-sum(Participant_Word_Task[[i]]$TotalTimePaused[1:WordFrame[i,11]])
> WordFrame[i,13] <-
> difftime(time(original_series[length(original_series)]),time(original_series[1]))
> WordFrame[i,14] <- length(original_series)
> WordFrame[i,15] <-
> sum(Participant_Word_Task[[i]]$TotalDuration[1:length(original_series)])-sum(Participant_Word_Task[[i]]$TotalTimePaused[1:length(original_series)])
>
>
> simplemovingaverage <- SMA(original_series, n =
> nweeks(original_series))
>
> if (WordFrame[i,4] <= 0.05 & WordFrame[i,6] <= 0.05 & WordFrame[i,8]
> <= 0.05){
>

Re: [R] Getting "Error in ect, plot.new has not been called yet" despite grouping plot call

2022-10-05 Thread Rolf Turner
quisition.pdf")
>   plout <- plot(original_series)
>   lines(simplemovingaverage)
>   abline(v = index(original_series[WordFrame[i,7]]),lty=2,
> col='green', lwd=3) title(paste("Word Task Acquisition for Subject"))
>   dev.off()
>  }
>   #If the three tests are NOT statistically significant, generate a
> plot with NO horizontal line at WordFrame[i,7] } else {
>     {
>   pdf(file = "Word_Task_Acquisition.pdf")
>   plout <- plot(original_series)
>   lines(simplemovingaverage)
>   title(paste("Word Task Acquisition for Subject"))
>   dev.off()
> }
>   }
> }
> 
> 
> From: Rolf Turner 
> Sent: Wednesday, October 5, 2022 6:06 AM
> To: Deramus, Thomas Patrick 
> Cc: r-help@r-project.org 
> Subject: Re: [R] Getting "Error in ect, plot.new has not been called
> yet" despite grouping plot call
> 
> External Email - Use Caution
> 
> What you doing or trying to do is far too complex for my poor feeble
> and senile brain to come anywhere near comprehending.  The code that
> you present exceeds my complexity tolerance by many orders of
> magnitude.
> 
> I have a suggestion, but.  Strip your code down to the *essentials*.
> Construct a simple sequence of plotting commands, with *simple* names
> for the pdf files involved.  You should require only two or three such
> files and two or three index levels associated with each of your
> nested loops.
> 
> Run the stripped down code and the source of the problem will almost
> surely become clear.
> 
> cheers,
> 
> Rolf Turner
> 
> On Tue, 4 Oct 2022 23:35:09 +
> "Deramus, Thomas Patrick"  wrote:
> 
> > Sorry to cross-post on Stackoverflow and here but I'm having some
> > difficulty.
> > https://secure-web.cisco.com/1_juqv4RvefQFJofsnOQcQA3Ixge89s4uC26pjoPBaYOSxSLGisKtgUTZkanxeHNRqNmjl30B8wYKfsppHje4T8Su77i7t8UbMKzs3GBKEyQva4yTjPH76Q9-l6tT24bB4qNMPQeFAxrkG5lpozNpGrDIAjfKCMvgS-5Qjs-QmvhWZfo84_3SK9rHhJjJvO9CqXb0MewWwI-dEmkZemjxnliGe_D9nooo7Ebjuw0dpBuMnrdaTzQxDdivsbkujPnrGurdjLARh93RW5IWPszNwaoziRD7P-30McF1PrAP8_yjWrhxQ_S3AgG6k40EoQJU/https%3A%2F%2Fstackoverflow.com%2Fquestions%2F73942794%2Fstill-getting-error-in-ect-plot-new-has-not-been-called-yet-despite-grouping
> >
> > Trying to make a nested loop that produces PDFs off different
> > graphs, one for ACF/PACF diagnostics and another for the actual
> > data, based on some time-series analyses I'm doing.
> >
> > Unfortunately, I keep getting the dreaded: Error plot.new has not
> > been called yet
> >
> > The code is meant to write a PDF containing the ACF and PACF graphs,
> > then do some analyses on the timeseries, and then make a separate
> > PDF containing a plot describing the timeseries based on the
> > p-values of each test for each individual.
> >
> > library(plyr)
> > library(dplyr)
> > library(ggplot2)
> > library(Kendall)
> > library(lubridate)
> > library(xts)
> > library(TTR)
> > library(trend)
> > library(forecast)
> > library(openxlsx)
> >
> > Game_Metrics_Word_Task <-
> > read.xlsx("GamePack_Analytics_ALL_TIME_Short.xlsx", "Boggle")
> > Game_Metrics_Word_Task <- Game_Metrics_Word_Task %>%
> > filter(grepl('1440', StudyId)) Game_Metrics_Word_Task$DeviceTime <-
> > ymd_hms(Game_Metrics_Word_Task$DeviceTime,  tz = "America/New_York")
> > Game_Metrics_Word_Task <-
> > Game_Metrics_Word_Task[!duplicated(Game_Metrics_Word_Task[1:2,])]
> >
> > Participant_Word_Task <-
> > split(arrange(Game_Metrics_Word_Task,StudyId,DeviceTime),
> > arrange(Game_Metrics_Word_Task,StudyId,DeviceTime,StudyId,DeviceTime)$StudyId)
> >
> > WordFrame <- data.frame(Participant = c(0), Task = c(0),
> > MannKendall_Tau = c(0), MannKendall_P = c(0), Sen_Slope_Value =
> > c(0), Sen_Slope_Pval = c(0), Pettitts_CIV = c(0), Pettitts_Pval =
> > c(0), ARIMA_Model = c(0), Time_to_Petit = c(0),
> > Number_of_Trials_to_Pettitt = c(0), Playtime_to_Petit_seconds =
> > c(0), Time_Start_to_end_days = c(0), Number_of_Total_Trials = c(0),
> > Total_Playtime_seconds = c(0), Learning_rate_days = c(0),
> > Learning_rate_seconds = c(0), Learned_Task = c(0))
> >
> > for (i in 1:length(Participant_Word_Task)){
> > success_series <- xts(filter(Participant_Word_Task[[i]],
> > GameEndReason == "TIMER_UP")$NumberOfSuccesfulWords ,
> > order.by=as.POSIXct(filter(Participant_Word_Task[[i]], GameEndReason
> > == "TIMER_UP")$DeviceTime)) original_series <-
> > xts(Participant_Word_Task[[i]]$Numb

Re: [R] Getting "Error in ect, plot.new has not been called yet" despite grouping plot call

2022-10-05 Thread Rolf Turner


What you doing or trying to do is far too complex for my poor feeble
and senile brain to come anywhere near comprehending.  The code that
you present exceeds my complexity tolerance by many orders of magnitude.

I have a suggestion, but.  Strip your code down to the *essentials*.
Construct a simple sequence of plotting commands, with *simple* names
for the pdf files involved.  You should require only two or three such
files and two or three index levels associated with each of your
nested loops.

Run the stripped down code and the source of the problem will almost
surely become clear.

cheers,

Rolf Turner

On Tue, 4 Oct 2022 23:35:09 +
"Deramus, Thomas Patrick"  wrote:

> Sorry to cross-post on Stackoverflow and here but I'm having some
> difficulty.
> https://stackoverflow.com/questions/73942794/still-getting-error-in-ect-plot-new-has-not-been-called-yet-despite-grouping
> 
> Trying to make a nested loop that produces PDFs off different graphs,
> one for ACF/PACF diagnostics and another for the actual data, based
> on some time-series analyses I'm doing.
> 
> Unfortunately, I keep getting the dreaded: Error plot.new has not
> been called yet
> 
> The code is meant to write a PDF containing the ACF and PACF graphs,
> then do some analyses on the timeseries, and then make a separate PDF
> containing a plot describing the timeseries based on the p-values of
> each test for each individual.
> 
> library(plyr)
> library(dplyr)
> library(ggplot2)
> library(Kendall)
> library(lubridate)
> library(xts)
> library(TTR)
> library(trend)
> library(forecast)
> library(openxlsx)
> 
> Game_Metrics_Word_Task <-
> read.xlsx("GamePack_Analytics_ALL_TIME_Short.xlsx", "Boggle")
> Game_Metrics_Word_Task <- Game_Metrics_Word_Task %>%
> filter(grepl('1440', StudyId)) Game_Metrics_Word_Task$DeviceTime <-
> ymd_hms(Game_Metrics_Word_Task$DeviceTime,  tz = "America/New_York")
> Game_Metrics_Word_Task <-
> Game_Metrics_Word_Task[!duplicated(Game_Metrics_Word_Task[1:2,])]
> 
> Participant_Word_Task <-
> split(arrange(Game_Metrics_Word_Task,StudyId,DeviceTime),
> arrange(Game_Metrics_Word_Task,StudyId,DeviceTime,StudyId,DeviceTime)$StudyId)
> 
> WordFrame <- data.frame(Participant = c(0), Task = c(0),
> MannKendall_Tau = c(0), MannKendall_P = c(0), Sen_Slope_Value = c(0),
> Sen_Slope_Pval = c(0), Pettitts_CIV = c(0), Pettitts_Pval = c(0),
> ARIMA_Model = c(0), Time_to_Petit = c(0), Number_of_Trials_to_Pettitt
> = c(0), Playtime_to_Petit_seconds = c(0), Time_Start_to_end_days =
> c(0), Number_of_Total_Trials = c(0), Total_Playtime_seconds = c(0),
> Learning_rate_days = c(0), Learning_rate_seconds = c(0), Learned_Task
> = c(0))
> 
> for (i in 1:length(Participant_Word_Task)){
> success_series <- xts(filter(Participant_Word_Task[[i]],
> GameEndReason == "TIMER_UP")$NumberOfSuccesfulWords ,
> order.by=as.POSIXct(filter(Participant_Word_Task[[i]], GameEndReason
> == "TIMER_UP")$DeviceTime)) original_series <-
> xts(Participant_Word_Task[[i]]$NumberOfSuccesfulWords,
> order.by=as.POSIXct(Participant_Word_Task[[i]]$DeviceTime))
> success_decomp <- ts(success_series, frequency =
> nweeks(success_series)) original_decomp <- ts(original_series,
> frequency = nweeks(success_series))
> 
> 
> pdf(paste("Word_Task_Autocorrelation_plots_for_subject_",unique(Participant_Word_Task[[i]]$StudyId),".pdf"
> ,collapse = NULL, sep = "")) par(mfrow=c(1,2))
> Autocorrelationplot <- acf(success_decomp, main=paste(""))
> PartialAutocorrelationplot <- pacf(success_decomp, main=paste(""))
> mtext(paste("Word Task Auto and Partialauto correlations for
> subject ",unique(Participant_Word_Task[[i]]$StudyId)), side = 3, line
> = -3, outer = TRUE) dev.off()
> 
> AutomatedArimaoutputs <- auto.arima(success_decomp)
> p <- length(AutomatedArimaoutputs$model$phi)
> #AR component
> q <- length(AutomatedArimaoutputs$model$theta)
> #MA component
> d <- AutomatedArimaoutputs$model$Delta
> #order of difference
> WordFrame[i,1] <- unique(Participant_Word_Task[[i]]$StudyId)
> WordFrame[i,2] <- "Word"
> WordFrame[i,3] <- MannKendall(success_decomp)$tau[1]
> WordFrame[i,4] <- MannKendall(success_decomp)$sl[1]
> WordFrame[i,5] <- sens.slope(success_decomp)$estimates
> WordFrame[i,6] <- sens.slope(success_decomp)$p.value
> WordFrame[i,7] <- pettitt.test(success_decomp)$estimate
> WordFrame[i,8] <- pettitt.test(success_decomp)$p.value
> WordFrame[i,9] <- paste("ARIMA(",p,",",q,",",d,")", collapse =
> NULL, sep = "") WordFrame[i,10] <-
> difftime(time(success_series[WordFrame[i,7]]),time(original_series[1]))
> WordFrame[i,11] <- tail(which(grepl(success_series[WordFrame[i,7]],
> original_series)), n=1) WordFrame[i,12] <-
> sum(Participant_Word_Task[[i]]$TotalDuration[1:WordFrame[i,11]])-sum(Participant_Word_Task[[i]]$TotalTimePaused[1:WordFrame[i,11]])
> WordFrame[i,13] <-
> difftime(time(original_series[length(original_series)]),time(original_series[1]))
> WordFrame[i,14] <- 

[R] Getting "Error in ect, plot.new has not been called yet" despite grouping plot call

2022-10-05 Thread Deramus, Thomas Patrick
Sorry to cross-post on Stackoverflow and here but I'm having some difficulty.
https://stackoverflow.com/questions/73942794/still-getting-error-in-ect-plot-new-has-not-been-called-yet-despite-grouping

Trying to make a nested loop that produces PDFs off different graphs, one for 
ACF/PACF diagnostics and another for the actual data, based on some time-series 
analyses I'm doing.

Unfortunately, I keep getting the dreaded: Error plot.new has not been called 
yet

The code is meant to write a PDF containing the ACF and PACF graphs, then do 
some analyses on the timeseries, and then make a separate PDF containing a plot 
describing the timeseries based on the p-values of each test for each 
individual.

library(plyr)
library(dplyr)
library(ggplot2)
library(Kendall)
library(lubridate)
library(xts)
library(TTR)
library(trend)
library(forecast)
library(openxlsx)

Game_Metrics_Word_Task <- read.xlsx("GamePack_Analytics_ALL_TIME_Short.xlsx", 
"Boggle")
Game_Metrics_Word_Task <- Game_Metrics_Word_Task %>% filter(grepl('1440', 
StudyId))
Game_Metrics_Word_Task$DeviceTime <- ymd_hms(Game_Metrics_Word_Task$DeviceTime, 
 tz = "America/New_York")
Game_Metrics_Word_Task <- 
Game_Metrics_Word_Task[!duplicated(Game_Metrics_Word_Task[1:2,])]

Participant_Word_Task <- 
split(arrange(Game_Metrics_Word_Task,StudyId,DeviceTime), 
arrange(Game_Metrics_Word_Task,StudyId,DeviceTime,StudyId,DeviceTime)$StudyId)

WordFrame <- data.frame(Participant = c(0), Task = c(0), MannKendall_Tau = 
c(0), MannKendall_P = c(0), Sen_Slope_Value = c(0), Sen_Slope_Pval = c(0), 
Pettitts_CIV = c(0), Pettitts_Pval = c(0), ARIMA_Model = c(0), Time_to_Petit = 
c(0), Number_of_Trials_to_Pettitt = c(0), Playtime_to_Petit_seconds = c(0), 
Time_Start_to_end_days = c(0), Number_of_Total_Trials = c(0), 
Total_Playtime_seconds = c(0), Learning_rate_days = c(0), Learning_rate_seconds 
= c(0), Learned_Task = c(0))

for (i in 1:length(Participant_Word_Task)){
success_series <- xts(filter(Participant_Word_Task[[i]], GameEndReason == 
"TIMER_UP")$NumberOfSuccesfulWords , 
order.by=as.POSIXct(filter(Participant_Word_Task[[i]], GameEndReason == 
"TIMER_UP")$DeviceTime))
original_series <- xts(Participant_Word_Task[[i]]$NumberOfSuccesfulWords, 
order.by=as.POSIXct(Participant_Word_Task[[i]]$DeviceTime))
success_decomp <- ts(success_series, frequency = nweeks(success_series))
original_decomp <- ts(original_series, frequency = nweeks(success_series))


pdf(paste("Word_Task_Autocorrelation_plots_for_subject_",unique(Participant_Word_Task[[i]]$StudyId),".pdf"
 ,collapse = NULL, sep = ""))
par(mfrow=c(1,2))
Autocorrelationplot <- acf(success_decomp, main=paste(""))
PartialAutocorrelationplot <- pacf(success_decomp, main=paste(""))
mtext(paste("Word Task Auto and Partialauto correlations for subject 
",unique(Participant_Word_Task[[i]]$StudyId)), side = 3, line = -3, outer = 
TRUE)
dev.off()

AutomatedArimaoutputs <- auto.arima(success_decomp)
p <- length(AutomatedArimaoutputs$model$phi)
#AR component
q <- length(AutomatedArimaoutputs$model$theta)
#MA component
d <- AutomatedArimaoutputs$model$Delta
#order of difference
WordFrame[i,1] <- unique(Participant_Word_Task[[i]]$StudyId)
WordFrame[i,2] <- "Word"
WordFrame[i,3] <- MannKendall(success_decomp)$tau[1]
WordFrame[i,4] <- MannKendall(success_decomp)$sl[1]
WordFrame[i,5] <- sens.slope(success_decomp)$estimates
WordFrame[i,6] <- sens.slope(success_decomp)$p.value
WordFrame[i,7] <- pettitt.test(success_decomp)$estimate
WordFrame[i,8] <- pettitt.test(success_decomp)$p.value
WordFrame[i,9] <- paste("ARIMA(",p,",",q,",",d,")", collapse = NULL, sep = 
"")
WordFrame[i,10] <- 
difftime(time(success_series[WordFrame[i,7]]),time(original_series[1]))
WordFrame[i,11] <- tail(which(grepl(success_series[WordFrame[i,7]], 
original_series)), n=1)
WordFrame[i,12] <- 
sum(Participant_Word_Task[[i]]$TotalDuration[1:WordFrame[i,11]])-sum(Participant_Word_Task[[i]]$TotalTimePaused[1:WordFrame[i,11]])
WordFrame[i,13] <- 
difftime(time(original_series[length(original_series)]),time(original_series[1]))
WordFrame[i,14] <- length(original_series)
WordFrame[i,15] <- 
sum(Participant_Word_Task[[i]]$TotalDuration[1:length(original_series)])-sum(Participant_Word_Task[[i]]$TotalTimePaused[1:length(original_series)])


simplemovingaverage <- SMA(original_series, n = nweeks(original_series))

if (WordFrame[i,4] <= 0.05 & WordFrame[i,6] <= 0.05 & WordFrame[i,8] <= 
0.05){
  {
  pdf(paste(WordFrame[i,1],"_Word_Task_Acquisition.pdf",collapse = 
NULL, sep = ""))
  plout <- plot(original_series,type='l',col='blue',xlab="Date of 
Play",ylab="Number of Successful Words")
  lines(simplemovingaverage,type='l',col='red')
  title(paste("Word Task Acquisition for Subject", WordFrame[i,1]))
  abline(v = index(original_series[WordFrame[i,7]]),lty=2, 
col='green',