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

时间:2016-11-11 04:17:22

标签: r replace gsub quantmod string-substitution

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

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,但没有任何成功 - 无法找出合适的语法。任何帮助,将不胜感激。感谢。

2 个答案:

答案 0 :(得分:1)

使用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)

答案 1 :(得分:1)

在学习R时,您可能会发现使用库gsub中的函数对字符串进行操作更容易,而不是在学习R时使用?regexstringr等基本R函数。您可以使用str_replace

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