搜索并替换字符串列表-gsub是否有效? [英] Search-and-replace on a list of strings - gsub eapply?
本文介绍了搜索并替换字符串列表-gsub是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我的代码的简化摘录,以供复制:
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)
}
然后,我的数据存储在此环境stockData中,我用它来进行一些分析.我想清理当前xts对象的名称:
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"
我想从所有名称中删除-和.TO,并尝试使用gsub和eapply,但没有成功-无法找出合适的语法.任何帮助,将不胜感激.谢谢.
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.
推荐答案
使用as.list
和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)
这篇关于搜索并替换字符串列表-gsub是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文