R Error in rep(X) : invalid ‘times’ argument (2 Examples)

 

In this post you’ll learn how to handle the “Error in rep(X) : invalid ‘times’ argument” in the R programming language.

The article will contain two examples for the handling of the “Error in rep(X) : invalid ‘times’ argument”. To be more specific, the content is structured as follows:

Let’s dive into it!

 

Example 1: Reproduce the Error in rep(X) : invalid ‘times’ argument

Example 1 explains how to replicate the “Error in rep(X) : invalid ‘times’ argument” in the R programming language.

Have a look at the following application of the rep function:

rep("a", - 5)                     # Application of rep doesn't work
# Error in rep("a", -5) : invalid 'times' argument

As you can see, the previous R code has returned the error message “Error in rep(X) : invalid ‘times’ argument”.

The reason for this error is that we have tried to use a negative times value (i.e. – 5).

Let’s fix this problem!

 

Example 2: Fix the Error in rep(X) : invalid ‘times’ argument

The following code demonstrates how to debug the “Error in rep(X) : invalid ‘times’ argument”.

For this, we have to assign a positive value to the times argument:

rep("a", 5)                       # Properly apply rep function
# [1] "a" "a" "a" "a" "a"

The previous R code has worked fine and has not returned any error messages.

 

Video & Further Resources

Do you need more explanations on the R syntax of the present tutorial? Then you may have a look at the following video on my YouTube channel. In the video, I’m explaining the contents of this tutorial:

 

The YouTube video will be added soon.

 

Besides the video, you might have a look at some of the related R programming posts on this website:

 

Summary: This article has shown how to properly replicate a value and how to avoid the “Error in rep(X) : invalid ‘times’ argument” in the R programming language. Let me know in the comments below, if you have further questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


2 Comments. Leave new

  • Palin Lertpoonwasin
    May 13, 2022 7:09 am

    When I run this code, it shows the error on the console.

    model <- forecast:::forecast.HoltWinters(mod, h=(length(data) – length(dataTrain)))

    Error in rep(as.vector(object$coefficients[1L]), n.ahead) :
    invalid 'times' argument

    Also,…
    Another code that I run does not work as well.

    comp <- cbind(dataTest,fc)

    Error in .cbind.ts(list(…), .makeNamesTs(…), dframe = FALSE, union = TRUE) :
    non-time series not of the correct length

    This is all the codes that I try to use for HoltWinters Forecast

    library(tidyverse)
    library(googleAuthR)
    library(googleAnalyticsR)
    library(forecast)
    library(reshape2)
    library(scales)
    library(dplyr)
    library(reprex)

    ga_auth()

    ga_account_list()

    metadata <- ga_meta(version = "universal", propertyId = 235022546)

    ga_id <- 235022546

    BaNANA_gadata2 <- google_analytics_3(id = ga_id,
    start = "2021-05-15",
    end = "2022-04-30",
    metrics = "ga:organicSearches",
    dimensions = "ga:date")

    plot(BaNANA_gadata2)

    BaNANA_gadata2

    data <- BaNANA_gadata2

    data.ts <- as.ts(data)

    data.ts

    plot(data.ts, type = 'b', col = "blue", main = colnames(data.ts))

    #Training and Test Split

    split <- ceiling(0.7 * length(data))
    dataTrain <- ts(data[1:split], frequency = 15, start = c(2021,5))
    dataTest <- ts(data[c((split+1) : nrow(data)),], frequency = 15, start = c(2022,5))
    actual <- unclass(dataTrain)
    actualFull <- unclass(data)

    forecastGen <- function(metd){

    if(metd == "HoltWinters"){
    method <- "HoltWinters {stats}"
    mod <- HoltWinters(dataTrain, optim.start = c(alpha = 0.99, beta = 0.001, gamma = 0.001))
    model <- forecast:::forecast.HoltWinters(mod, h=(length(data) – length(dataTrain)))
    actualFull <- actualFull[16:length(actualFull)]
    actual <- actual[16:length(actual)]
    i = 4
    }

    if(metd == "hw"){
    method <- "hw {forecast}"
    model <- hw(dataTrain, initial = "optimal", h=(length(data) – length(dataTrain)))
    i = 2
    }

    filename <- paste(method, ".png", sep = "")

    fit <- as.data.frame(model$fitted)[,1] # Fitted Values

    fitV <- unclass(fit)

    fc <- unlist(model[i])

    names(fc) <- NULL

    fitForecast <- (c(fit,fc))

    comp <- cbind(dataTest,fc)

    compFull <- cbind(actualFull, fitForecast)

    cat("Accuracy of Model:", metd,"\n")

    print(accuracy(model))

    mape <- round(mean(abs((comp[,2]-comp[,1])/comp[,1]))*100,2)

    cat("\n", paste("MAPE of Predictions =", mape), "\n\n")

    upper <- c(actual,model$upper[,1])

    lower <- c(actual,model$lower[,1])

    #Plot and Save

    png(file = filename,width = 900,height = 550)
    plot(actualFull, type = 'l', col = 'black', lwd = 2.5, main = method,
    ylab = colnames(data.ts), xlab = "Time Intervals", ylim = c(min(lower),max(upper)))
    grid()
    lines(fitForecast, type = 'l', col = 'red', lwd = 2)
    lines(fitV, type = 'l', col = 'blue', lwd = 3)
    lines(upper, col = "orange", lwd = 0.5)
    lines(lower, col = "orange", lwd = 0.5)
    legend("bottomright", inset = .01, c("Actual","Fitted","Predicted"),
    fill = c(1,4,2), horiz = TRUE, cex = 0.75)
    }

    # call the functions on HoltWinters() ad hw ()

    forecastGen(metd = "HoltWinters")
    forecastGen(metd = "hw")

    Reply
    • Hey Palin,

      What is returned to the console when you run the following code?

      length(data) – length(dataTrain)

      Regards,
      Joachim

      Reply

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top