-1

I have the following dataframe imported from excel using readxl in R. Is there a way to convert the column names to actual dates?

data <- structure(list(Model = c("ARIMA", "Actual", "Forecast", "Error"
), `44865` = c(NA, 1, 1, 0), `44895` = c(NA, 2, 2, 0), `44926` = c(NA, 
3, 3, 0)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-4L))

Tanga94
  • 695
  • 6
  • 27
  • 2
    I've reopened (from being a duplicate of https://stackoverflow.com/a/70304571/3358272) primarily because the problem is ever-so-slightly different: you are working with _names_ that are dates instead of values. I suggest two things: (1) never put "data" in a column name, instead reshape your data so that the dates are a field; (2) follow the link to learn how to convert those strings to dates. (R does not allow a column name to be anything other than `character`, so no `Date`-class is possible.) – r2evans Jan 24 '23 at 22:15
  • [Tidy data](https://vita.had.co.nz/papers/tidy-data.html) is a wonderful explanation of how organise data. – Isaiah Jan 25 '23 at 09:21

1 Answers1

0

In case you have a particular need for your column names to convey date...... though usually dates are data, and so go in rows rather than column names.

library(lubridate)

data_conv <- function(i) {
  colnames(data)[i] |>
  as.integer() |>
  as_date(origin = "1899-12-30") |>
  as.character()}

for (i in 2:4) {
  colnames(data)[i] <- data_conv(i)
}
Isaiah
  • 2,091
  • 3
  • 19
  • 28