R语言中移除字符向量部分内容及生成带.f后缀向量的方法
Got it, let's tackle these two R questions step by step!
When you pull financial data with getFinancials(), the resulting list gets names like GOOG.f—here's how you can strip that .f off the end:
Base R approach
Assuming your financial data list is stored in an object called fin_data:
# Get the current list names, then remove the .f suffix from the end names(fin_data) <- sub("\\.f$", "", names(fin_data))
The regex \\.f$ targets exactly .f at the end of each name (the \\. escapes the dot since it's a special character in regex, and $ anchors it to the end so we don't accidentally remove dots elsewhere).
Using stringr (tidyverse)
If you prefer the tidyverse syntax, stringr::str_remove() makes this even cleaner:
library(stringr) names(fin_data) <- str_remove(names(fin_data), "\\.f$")
To make a symbols.f vector that adds .f to each original symbol (great for avoiding conflicts with getSymbols()), you can use simple string concatenation:
Base R approach
Start with your original symbols vector, then use paste0() to append .f without extra spaces:
symbols <- c("HOC", "GOOG", "MSFT") # Example original symbols symbols.f <- paste0(symbols, ".f") # Result: c("HOC.f", "GOOG.f", "MSFT.f")
Using stringr (tidyverse)
Alternatively, stringr::str_c() works the same way:
library(stringr) symbols.f <- str_c(symbols, ".f")
This vector is ready to use wherever you need the suffixed symbol names, keeping things separate from your original symbols vector to prevent clashes with getSymbols().
内容的提问来源于stack exchange,提问作者user113156

