Error when updating a dataframe with new column inside a for loop using Dplyr

75 Views Asked by At

I have the following R dataframe df:

library(tidyquant)

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

assets_list <- c('DGS30', 'T10Y2Y')

for (asset in assets_list){
  
  assign(paste('sym', asset, sep = '_'), tq_get(asset,
                                                from = start_date,
                                                to = end_date,
                                                get = 'economic.data') %>%
           # renames the generic 'price' column
           rename({{asset}} := price) %>%
           
           # casts from a tibble to a data frame
           as.data.frame() %>%
           
           # removes NA values
           na.omit()
  )
}

# joins the data frames together
df <- list(sym_DGS30, sym_T10Y2Y) %>%
  reduce(full_join, by='date')

# specifies only the desired columns in the data frame
df <- subset(df, select = c(date, DGS30, T10Y2Y))

# sorts the 'date' column
df <- df[order(df$date, decreasing = FALSE),] 

head(df)
        date DGS30 T10Y2Y
1 2022-01-03  2.01   0.85
2 2022-01-04  2.07   0.89
3 2022-01-05  2.09   0.88
4 2022-01-06  2.09   0.85
5 2022-01-07  2.11   0.89
6 2022-01-10  2.11   0.86

I'd like to add a daily returns column for each of the two assets. To do so, I use the following:

for (asset in assets_list){
  
  assign(df, df %>%
           tq_mutate(
             select = asset,
             mutate_fun = periodReturn,
             period = 'daily',
             col_rename = paste('daily_return', asset, sep = '_')
           ))
}

But, I get the following error:

Error in assign(df, df %>% tq_mutate(select = asset, mutate_fun = periodReturn,  : 
  invalid first argument

Interestingly, the following blocks work individually (but not inside the for loop):

df <- df %>%
  tq_mutate(
    select = DGS30,
    mutate_fun = periodReturn,
    period = 'daily',
    col_rename = 'daily_return_DGS30'
  )

df <- df %>%
  tq_mutate(
    select = T10Y2Y,
    mutate_fun = periodReturn,
    period = 'daily',
    col_rename = 'daily_return_T10Y2Y'
  )

What am I doing wrong with the assignment?

Thanks!

1

There are 1 best solutions below

1
On BEST ANSWER

Assign can be a mess sometimes. I recommend just using mutate and calculating the returns yourself since it's a simple calculation.

df <- df %>%
mutate(
"daily_return_DGS30" = DGS30/lag(DGS30)-1,
"daily_return_T10Y2Y" = T10Y2Y/lag(T10Y2Y)-1
)