'Change column name with tq_get() in Tidyquant

I'm using the tq_get() function in Tidyquant to retrieve economic data from FRED:

library(tidyquant)
library(tidyverse)

consumer_price_index <- 'CPIAUCSL'

start_date <- as.Date('2022-01-01')
end_date <- as.Date('2022-03-31')

cpi <- tq_get(consumer_price_index,
               from = start_date,
               to = end_date,
               get = 'economic.data')

cpi

# A tibble: 3 x 3
  symbol   date       price
  <chr>    <date>     <dbl>
1 CPIAUCSL 2022-01-01  282.
2 CPIAUCSL 2022-02-01  284.
3 CPIAUCSL 2022-03-01  288.

How do I change the name of the price column to cpi?

The desired tibble would look as follows:

# A tibble: 3 x 3
  symbol   date        cpi
  <chr>    <date>     <dbl>
1 CPIAUCSL 2022-01-01  282.
2 CPIAUCSL 2022-02-01  284.
3 CPIAUCSL 2022-03-01  288.

Thanks!



Solution 1:[1]

You may use rename from dplyr

cpi <- tq_get(consumer_price_index,
              from = start_date,
              to = end_date,
              get = 'economic.data') %>% 
  rename(cpi = price)

# A tibble: 3 × 3
  symbol   date         cpi
  <chr>    <date>     <dbl>
1 CPIAUCSL 2022-01-01  282.
2 CPIAUCSL 2022-02-01  284.
3 CPIAUCSL 2022-03-01  288.

Or just use colnames from base

colnames(cpi)<- c("symbol", "date", "cpi")

Solution 2:[2]

Using column number:

names(cpi)[3] <- "cpi"
cpi

# A tibble: 3 x 3
  symbol   date         cpi
  <chr>    <date>     <dbl>
1 CPIAUCSL 2022-01-01  282.
2 CPIAUCSL 2022-02-01  284.
3 CPIAUCSL 2022-03-01  288.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Constanza Zepeda
Solution 2