Question

I have a problem while I am downloading the data from yahoo finance using quantmod. There are always a suffix number after the column ticker names that I want to remove.

My code as follow:

library("quantmod")
library("PerformanceAnalytics")
library("FinancialInstrument")

myenv <- new.env()
tickers <- c("LNKD", "FB", "HP", "AAPL", "MSFT", "GOOG", "EBAY")
getSymbols(tickers, env = myenv)
monthly.Return <- do.call(merge, c(eapply(myenv, monthlyReturn), all=FALSE))
names(monthly.Return)[1:10] <- paste(tickers, 1:10, sep="")
monthly.Return

The output:

LNKD1          FB2           HP3         AAPL4        MSFT5        GOOG6       EBAY7
2012-05-31 -0.117267081 -0.044978166 -0.0446123842 -0.0107024213 -0.118505546 -0.039662726 -0.11387736
2012-06-29  0.072333240  0.051668953  0.0719571319  0.0108528205 -0.040176600 -0.001360052  0.10582726
2012-07-31  0.039632546  0.045217391  0.0545108308  0.0458219178  0.069457222  0.091195890 -0.03406418
................................

And I want to remove the number after each column names.

Was it helpful?

Solution

> names(monthly.Return)
[1] "LNKD1" "FB2"   "HP3"   "AAPL4" "MSFT5" "GOOG6" "EBAY7"
> names(monthly.Return) <- gsub("[[:digit:]]", "", names(monthly.Return) )
> names(monthly.Return)
[1] "LNKD" "FB"   "HP"   "AAPL" "MSFT" "GOOG" "EBAY"

OTHER TIPS

Try

x
##  [1] "LNKD1" "FB2"   "HP3"   "AAPL4" "MSFT5" "GOOG6" "EBAY7" "LNKD8" "FB9"   "HP10" 

gsub("(.*)[0-9]+?", "\\1", x)
##  [1] "LNKD" "FB"   "HP"   "AAPL" "MSFT" "GOOG" "EBAY" "LNKD" "FB"   "HP"  

This removes trailing/ending Number but not the numbers in between

 names(monthly.Return)
 names(monthly.Return) <- gsub("[0-9]$", "", names(monthly.Return) )
 names(monthly.Return)

If you have more than one digit in the end then :

 names(monthly.Return)
 names(monthly.Return) <- gsub("[0-9]$|[0-9][0-9]$", "", names(monthly.Return) )
 names(monthly.Return)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top