1

I am trying to take financial data that has dates and create a summary table. In doing so, I transform the data to wide format and then want to rename the resulting new columns since they otherwise will show up as dates.

I believe I am providing a character vector to "vars" when using "rename_at", but it is throwing an error and I am stuck as to why. I found this link here as an example of how to rename multiple columns rename example

The desired output would look like this:

enter image description here

Reproducible example

library(tidyverse)
library(lubridate)

# data
my_dates <- as.Date(c("2018-05-25", "2018-08-25", "2018-11-25", "2018-05-25", "2018-08-25", "2018-11-25"))
item     <- c("A","A","A","B","B","B")
value    <- c(50:55)

df <- data.frame(my_dates, item, value)

# Dates will become column names and coerced as characters, so need way to refer to them
my_colnames  <- as.character(sort(my_dates, decreasing = TRUE))

# New column names
new_colnames <- c("current", "3M_ago", "6M_ago")

# convert to wide format
df_wide <- df %>%
    spread(key = my_dates, value) %>%
    select(item, my_colnames) %>%
    rename_at(vars(my_colnames) ~ new_colnames)  # throws error here

Thanks in advance for the help!

DaveM
  • 664
  • 6
  • 19
  • I just updated all of my packages, reran the code, but still get "Error: `.vars` must be a character/numeric vector or a `vars()` object, not formula" – DaveM Dec 01 '18 at 17:44

1 Answers1

1

We need a , before the ~. The ~ part is similar to anonymous function call instead of a formula object with vars

library(tidyverse)
df %>%
   spread(key = my_dates, value) %>%
   select(item, my_colnames) %>%
   rename_at(vars(my_colnames), ~ new_colnames)
#  item current 3M_ago 6M_ago
#1    A      52     51     50
#2    B      55     54     53
akrun
  • 874,273
  • 37
  • 540
  • 662