Search code examples
rquantmod

Remove part of a character vector in r


I am running the following

# rm(list=ls(all=TRUE))  #It's more courteous to make that as a comment.

library(quantmod)
symbols <- c("HOG", "GE", "GOOG")

for (i in 1:length(symbols)) {   
  getFinancials(symbols[i], src="yahoo", auto.assign = TRUE)
}

Which download balance sheet information for 3 firms in symbols. However when I call the getFinancials function it creates an addition to the list name. For example GOOG.f. I have two questions.

Question 1: How can I first remove the .f part from the list. Question 2: If I want to keep the .f (as removing it will cause conflicts if I want to use getSymbols how can I write a new symbols character value but with the addition to .f

For example symbols.f <- c("HOC.f", "GOOG.f", "GE.f")


Solution

  • You can use paste0 to add the .f and sub to take it off.

    symbols <- c("HOG", "GE", "GOOG")
    
    ( symbols.f <- paste0(symbols, ".f") )
    [1] "HOG.f"   "GE.f" "GOOG.f"
    
    sub("\\.f","", symbols.f)  #Periods (regex metacharacter) need to be double escaped.
    [1] "HOC"  "GOOG" "GE"