1

I've tried to automate this and searched around but it's not fruitful. I downloaded the following data from Yahoo Finance.

require(quantmod)

tickers <- c("SPY")
start <- "2020-01-01"
end   <- "2020-06-01"

 getSymbols(tickers,
             from = start,
             to = end,
             env = globalenv())

Now, I would like to replace all the values in SPY$open, SPY$close, ..., if the index(data) is before "2020-05-01". I tried to work with the xts format but I couldn't do it so I decided to convert it to data.frame by:

data = SPY # I create this so I can scale up the code for not only SPY.

data$day <- as.Date(data$day) # format day.
colnames(data) <- c("day", "open", "high", "low", "close", "volume", "adjusted_price")
to_replace <- c("day", "open", "high", "low", "close", "volume", "adjusted_price")

Now, I can run the following code for one column

  data$open <- ifelse(data$day < as.Date("2020-05-01"), data$open/100, data$open)

How can I make an automated code to run for all columns named in to_replace. I tried to make a function and apply lapply like this but it didn't work.

  replace <- function(x) {
    x <- ifelse(data$day > as.Date("2020-05-1"), x/100, x)
    return(x)
  }

lappy(tickers, replace)

In general, I have two questions.

  1. How can we run a function over the values of multiple columns under some condition?
  2. Can we do all this within xts frame instead of data frame?
Khan
  • 147
  • 1
  • 7

1 Answers1

0

You can try with across from dplyr 1.0.0:

library(dplyr)

data <- data.frame(date=index(SPY), coredata(SPY))

colnames(data) <- c("day", "open", "high", "low", "close", "volume", "adjusted_price")
to_replace <- c("open", "high", "low", "close", "volume", "adjusted_price")

data <- data %>% 
  mutate(across(to_replace, ~ if_else(day >  as.Date("2020-05-1"), . / 100, .)))

Chris
  • 266
  • 1
  • 6