JohnS
JohnS

Reputation: 21

How Do You Execute If-Then Logic On All The Columns Of An xts object in R

I have an xts object with multiple columns in R and I want to convert all the numbers larger than, say, 0.05 to NA (or -99 or something like that).

To get some data to execute on please do the following.

library(purrr); library(quantmod)

GetMySymbols <- function(x) { 
   getSymbols(x, src="yahoo", from='2023-06-01', to='2024-04-01', auto.assign=FALSE)
}
tickers <- c('AAPL','BAC','MSFT','GOOGL','SWKS')
Prices <- map(tickers, GetMySymbols)
Prices <- Prices %>% map(Ad) %> %reduce(merge.xts)
names(Prices) <- tickers
Returns <- diff(Prices, 1, arith=FALSE)-1
#Returns
Max90 <- rollmax(Returns, 90)
Max90 <- na.omit(Max90)

So now I want to adjust any value larger than 0.05 to NA for all the five columns of the object Max90. I have been googling for a number of hours but I think that this is so simple that there is not a good example out there.

Help would be much appreciated.

I tried a number of hacks of example code out on Stack overflow but I couldn't get them to work.

I expect that any number larger than 0.05 to be modified.

Upvotes: 0

Views: 44

Answers (1)

Edward
Edward

Reputation: 19494

You could use apply to loop through the columns:

Max90_NA <- as.xts(apply(Max90, 2, function(x) ifelse(x>0.05 , NA, x)))
head(Max90_NA)
                 AAPL        BAC       MSFT GOOGL       SWKS
2023-08-07 0.02310252 0.04421772 0.03979977    NA 0.03590555
2023-08-08 0.02310252 0.04421772 0.03979977    NA 0.03590555
2023-08-09 0.02310252 0.04421772 0.03979977    NA 0.03590555
2023-08-10 0.02310252 0.04421772 0.03979977    NA 0.03590555
2023-08-11 0.02310252 0.04421772 0.03979977    NA 0.03590555
2023-08-14 0.02310252 0.04421772 0.03979977    NA 0.03590555

Upvotes: 2

Related Questions