Home > Mobile >  Rename() function in R not working with Dplyr pipe inside for loop
Rename() function in R not working with Dplyr pipe inside for loop

Time:04-29

I retrieve a bunch of data using the Tidyquant API, as follows:

library(tidyquant)

symbols_list <- c('DGS2', 'DGS5', 'DGS10', 'DGS30')
start_date <- as.Date('2022-01-01')
end_date <- as.Date('2022-03-31')

for (asset in symbols_list){
  
  # retrieves the data
  assign(paste('sym', asset, sep = '_'), tq_get(asset,
                                                 from = start_date,
                                                 to = end_date,
                                                 get = 'economic.data') %>%
        )

}

The data looks as follows:

sym_DGS5

# A tibble: 64 x 3
   symbol date       price
   <chr>  <date>     <dbl>
 1 DGS5   2022-01-03  1.37
 2 DGS5   2022-01-04  1.37
 3 DGS5   2022-01-05  1.43
 4 DGS5   2022-01-06  1.47
 5 DGS5   2022-01-07  1.5 
 6 DGS5   2022-01-10  1.53
 7 DGS5   2022-01-11  1.51
 8 DGS5   2022-01-12  1.5 
 9 DGS5   2022-01-13  1.47
10 DGS5   2022-01-14  1.55
# ... with 54 more rows

I would like to rename the generic price column with the names of the symbols. In this case, I would like to rename "price" as "DGS5" To do so, I use the rename() function and the dpyr pipe, as follows:

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

symbol_list <- c('T10Y2Y', 'DGS2', 'DGS5', 'DGS10', 'DGS30')
symbol_list 

for (asset in symbol_list){
  
   # retrieves the data
   assign(paste('sym', asset, sep = '_'), tq_get(asset,
                                              from = start_date,
                                              to = end_date,
                                              get = 'economic.data'
                                              ) %>% rename(asset = price)
          )
}

But, doing so gives:

sym_DGS5

# A tibble: 64 x 3
   symbol date       asset
   <chr>  <date>     <dbl>
 1 DGS5   2022-01-03  1.37
 2 DGS5   2022-01-04  1.37
 3 DGS5   2022-01-05  1.43
 4 DGS5   2022-01-06  1.47
 5 DGS5   2022-01-07  1.5 
 6 DGS5   2022-01-10  1.53
 7 DGS5   2022-01-11  1.51
 8 DGS5   2022-01-12  1.5 
 9 DGS5   2022-01-13  1.47
10 DGS5   2022-01-14  1.55
# ... with 54 more rows

Notice how the column was renamed to "asset". I would have expected the column to be renamed to "DGS5".

What did I do incorrectly here?

Thanks!

CodePudding user response:

Note that you have a data-variable in a function argument (i.e. an env-variable that holds a promise, you need to embrace the argument by surrounding it in doubled braces. This is called [INDIRECTION], which is a glue syntax.

If you want to use the names of variables in the output, you can use glue syntax in conjunction with :=

Therefore you get

rename({{asset}} = price)

Check here for more information

  • Related