r语言 - 在Tidyquant中使用tq_get()更改列名



我正在使用Tidyquant中的tq_get()函数从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.

如何将"price"列的名称修改为"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.

谢谢!

您可以使用dplyr中的rename

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.

或者直接使用base

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

使用列号:

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.

相关内容

  • 没有找到相关文章

最新更新