Change column name with tq_get() in Tidyquant

101 Views Asked by At

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!

2

There are 2 best solutions below

0
On BEST ANSWER

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")
0
On

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.