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

Deramus, Thomas Patrick tder@mu@ @end|ng |rom p@rtner@@org
Wed Oct 5 01:35:09 CEST 2022

Sorry to cross-post on Stackoverflow and here but I'm having some difficulty.

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.


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 = ""))
    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)

    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")
              title(paste("Word Task Acquisition for Subject", WordFrame[i,1]))
              abline(v = index(original_series[WordFrame[i,7]]),lty=2, col='green', lwd=3)
              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(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")
              title(paste("Word Task Acquisition for Subject", WordFrame[i,1]))
              WordFrame[i,18] <- F
              WordFrame[i,16] <- 0
              WordFrame[i,17] <- 0

It will work just fine if I run the lines individually (e.g. set i = 1, 2, ect), and if I comment out abline and title (lines seems to work fine). But it will throw the error everytime I try to run the loop without these commented.

Have tried just about everything I could find on the Stack forums to run everything as a single argument and I'm just not sure what is wrong with it.

dev.list() spits out:

following the error.

With abline and title commented out and lines run individually it's NULL.

Happens in both RStudio

2022.07.2+576 "Spotted Wakerobin" Release (e7373ef832b49b2a9b88162cfe7eac5f22c40b34, 2022-09-06) for Ubuntu Bionic
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) QtWebEngine/5.12.8 Chrome/69.0.3497.128 Safari/537.36

And R:

platform       x86_64-pc-linux-gnu
arch           x86_64
os             linux-gnu
system         x86_64, linux-gnu
major          4
minor          2.1
year           2022
month          06
day            23
svn rev        82513
language       R
version.string R version 4.2.1 (2022-06-23)
nickname       Funny-Looking Kid

My OS:
PRETTY_NAME="Debian GNU/Linux 11 (bullseye)"
NAME="Debian GNU/Linux"
VERSION="11 (bullseye)"
No LSB modules are available.
Distributor ID:   Debian
Description:      Debian GNU/Linux 11 (bullseye)
Release:    11
Codename:   bullseye
         Icon name: computer-desktop
           Chassis: desktop
        Machine ID: 053ebf23707f49c8ad4e0684f4cf19d3
           Boot ID: d0e6294d3b944286bef10e76c21e6401
  Operating System: Debian GNU/Linux 11 (bullseye)
            Kernel: Linux 5.10.0-18-amd64
      Architecture: x86-64

Any suggestions would be greatly appreciated.


Thomas DeRamus (He/Him/His)

Data Analyst

Massachusetts General Hospital Brigham

Alzheimer’s Clinical & Translational Research Unit

149 13th Street

Charlestown, MA 02129

Phone: 205-834-5066

Email: tderamus using partners.org<mailto:tderamus using partners.org>, tpderamus using gmail.com<mailto:tpderamus using gmail.com>


“If knowledge can create problems, it is not through ignorance that we can solve them.”

—Issac Asimov
The information in this e-mail is intended only for the person to whom it is addressed.  If you believe this e-mail was sent to you in error and the e-mail contains patient information, please contact the Mass General Brigham Compliance HelpLine at https://www.massgeneralbrigham.org/complianceline <https://www.massgeneralbrigham.org/complianceline> .
Please note that this e-mail is not secure (encrypted).  If you do not wish to continue communication over unencrypted e-mail, please notify the sender of this message immediately.  Continuing to send or respond to e-mail after receiving this message means you understand and accept this risk and wish to continue to communicate over unencrypted e-mail. 

More information about the R-help mailing list