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

前提是你 提交于 2019-12-08 12:25:19

问题


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.


回答1:


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)



回答2:


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", "")))


来源:https://stackoverflow.com/questions/40541036/search-and-replace-on-a-list-of-strings-gsub-eapply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!