在字符串列表上搜索并替换 - gsub eapply?

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

这里是我的代码的简化摘录,用于复制目的:

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 对象的名称,目前是:

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

我想从所有名称中删除 - 和 .TO,并尝试使用 gsub 和 eapply,但没有成功 - 无法找到合适的语法。任何帮助,将不胜感激。谢谢

使用 as.listgsub:

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)

学习 R 时,与其使用 gsub?regex 等基本 R 函数,您可能会发现使用库 stringr 中的函数对字符串进行操作要容易得多。您可以使用 str_replace:

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