[英]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. 然后,我的数据存储在此环境stockData中,我用它进行一些分析。 I'd like to clean up the names of the xts objects, which are currently:
我想清理当前xts对象的名称:
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. 我想从所有名称中删除-和.TO,并尝试使用gsub和eapply,但没有成功-无法找出适当的语法。 Any help would be appreciated.
任何帮助,将不胜感激。 Thanks.
谢谢。
Using as.list
and gsub
: 使用
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)
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
. 在学习R时,与其使用诸如
?regex
gsub
这样的基本R函数, stringr
通过库stringr
的函数对字符串进行操作要容易stringr
。 You can use str_replace
: 您可以使用
str_replace
:
library(stringr)
e.stocks <- list2env(setNames(lapply(stocksLst, function(x) y <- getSymbols(x, env = NULL)),
str_replace(str_replace(stocksLst, "-", ""), "\\.TO", "")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.