Adam Parker
Adam Parker

Reputation: 7

Search-and-replace on a list of strings - gsub eapply?

Here is a simplified excerpt of my code for reproduction purposes:

library("quantmod")
stockData <- new.env()
stocksLst <- c("AAB.TO", "BBD-B.TO", "BB.TO", "ZZZ.TO")
nrstocks = length(stocksLst)
startDate = as.Date("2016-09-01")

for (i in 1:nrstocks) {
    getSymbols(stocksLst[i], env = stockData, src = "yahoo", from = startDate)
}

My data is then stored in this environment stockData which I use to do some analysis. I'd like to clean up the names of the xts objects, which are currently:

ls(stockData)
[1] "AAB.TO"   "BB.TO"    "BBD-B.TO" "ZZZ.TO"

I want to remove the - and the .TO from all of the names, and have tried to use gsub and eapply, without any success- can't figure out the appropriate syntax. Any help would be appreciated. Thanks.

Upvotes: 0

Views: 675

Answers (2)

FXQuantTrader
FXQuantTrader

Reputation: 6891

Instead of using base R functions like gsub with ?regex while learning R, you may find it much easier to operate on strings with the functions in library stringr. You can use str_replace:

library(stringr)
e.stocks <- list2env(setNames(lapply(stocksLst, function(x) y <- getSymbols(x, env = NULL)), 
                     str_replace(str_replace(stocksLst, "-", ""), "\\.TO", "")))

Upvotes: 1

Silence Dogood
Silence Dogood

Reputation: 3597

Using as.list and gsub:

library("quantmod")
stockData <- new.env()
stocksLst <- c("AAB.TO", "BBD-B.TO", "BB.TO", "ZZZ.TO")
nrstocks = length(stocksLst)
startDate = as.Date("2016-09-01")

for (i in 1:nrstocks) {
    getSymbols(stocksLst[i], env = stockData, src = "yahoo", from = startDate)
}

ls(stockData)
# [1] "AAB.TO"   "BB.TO"    "BBD-B.TO" "ZZZ.TO"

#convert to list for ease in manipulation
stockData = as.list(stockData)

#find . and replace everything after it with ""

names(stockData)=  gsub("[.].*$","",names(stockData))

#alternately you could match pattern .TO exactly and replace with ""

#names(stockData)=  gsub("[.]TO$","",names(stockData))

ls(stockData)
# [1] "AAB"   "BB"    "BBD-B" "ZZZ"  

#convert back to env 
list2env(stockData)

Upvotes: 1

Related Questions