在一组列上搜索和替换 - 尝试gsub时出错

时间:2016-11-12 02:32:34

标签: r gsub

这是此问题的后续行动:Search-and-replace on a list of strings - gsub eapply?

我有以下代码:

library(quantmod)
library(stringr)
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 = as.list(stockData)
names(stockData) = gsub("[.].*$", "", names(stockData))
names(stockData) = gsub("-", "", names(stockData))
symbolsLstCl <- ls(stockData)

最后一篇文章让我走了这么远,我非常感谢你的帮助。现在,我正在尝试对列名进行类似的替换,因为quantmod包含列中的符号名称:

colnames(stockData$ZZZ)
# [1] "ZZZ.TO.Open"     "ZZZ.TO.High"     "ZZZ.TO.Low"      "ZZZ.TO.Close"    "ZZZ.TO.Volume"   "ZZZ.TO.Adjusted"

我可以使用colnames轻松更新其中一个xts对象,但我希望将其包含在循环中,以便我可以对所有人进行操作。这是我尝试过的,但它失败了:

eval(parse(text = paste0("colnames(stockData$", symbolsLstCl[i], ")"))) <- eval(parse(text = (paste0("str_replace(colnames(stockData$", symbolsLstCl[i], "), ", "\".TO\", ", "\"\")"))))

我发现这很奇怪,好像我使用它(左侧是硬编码的),它有效:

colnames(stockData$ZZZ) <- eval(parse(text = (paste0("str_replace(colnames(stockData$", symbolsLstCl[i], "), ", "\".TO\", ", "\"\")"))))

我怀疑有更好的方法来更新这些列表中每个元素的所有列。任何建议都值得赞赏。谢谢,亚当

1 个答案:

答案 0 :(得分:1)

allnames <- lapply(stockData, 
                   function(x) names(x) = gsub(".TO", "", names(x)))

# replace column names
for (i in 1:length(stockData)) {
          names(stockData[[i]]) <- allnames[[i]]
}

# print all column names
for (i in 1:length(stockData)) {
          print(names(stockData[[i]]))
}

[1] "AAB.Open" "AAB.High" "AAB.Low" "AAB.Close" "AAB.Volume" "AAB.Adjusted"
[1] "BBD-B.Open" "BBD-B.High" "BBD-B.Low" "BBD-B.Close" "BBD-B.Volume" "BBD-B.Adjusted"
[1] "ZZZ.Open" "ZZZ.High" "ZZZ.Low" "ZZZ.Close" "ZZZ.Volume" "ZZZ.Adjusted"
[1] "BB.Open" "BB.High" "BB.Low" "BB.Close" "BB.Volume" "BB.Adjusted"

编辑:刚才输出不正确。

我想这是你希望得到的。