Search code examples
rstringcharacter

Creating a character vector with multiple sequences of data


I am trying to rename some data files using a character vector. Each file contains data corresponding to a month and year. I want to rename the files as such: "month_year".

I have successfully created the character vector as I want (see below) but I was wondering if there was a more succinct way to accomplish this. There must be a way to do this in one function, yes? Preferably in base R.

data.names <- expand.grid(month = c("June", "July", "August", "September"),
                          year = c(1984:2017),
                          stringsAsFactors = FALSE)
data.names <- as.character(c(paste0(data.names$month, "_", data.names$year)))

Solution

  • We may use rep

    out <- paste0(month.name[6:9],  "_", rep(1984:2017, each = 4))
    

    -testing with OP's code

    > out_prev <- as.character(c(paste0(data.names$month, "_", data.names$year)))
    > identical(out, out_prev)
    [1] TRUE