JKFY13
JKFY13

Reputation: 77

Renaming column in R

I'm totally new to R and programming!

I'm importing daily stock data using quantmod in R. I've created an object to import all the data at once.

MyStock <- c("AAPL","FB",...)

The names of each column includes the ticker name (eg. AAPL.Open) which I would simply like to rename (Open). I can do that with colnames() for each ticker but I would like to do it using my object to save time. How do I do that?

Thanks!

Upvotes: 0

Views: 1490

Answers (2)

Amrita Sawant
Amrita Sawant

Reputation: 10913

Gsub as mentioned above or use the Strsplit function Depending on where AAPL.Open appears in the colnames & extract the corresponding element. Something like below :

   MyStock <- c("AAPL.OPen.XX","FB.AAPL.Open.XX")
   MyStock <- sapply(strsplit(MyStock, "AAPL."), "[", 2)

Upvotes: 2

RockScience
RockScience

Reputation: 18580

You can try using gsub to remove the ticker name from the columns:

colnames(MyStock) = gsub(pattern = "AAPL.", replacement = "", x = colnames(MyStock), fixed = TRUE)

However
1. as suggested by Joshua, you'd better provide with a reproducible example otherwise people will struggle to understand exactly your question and will not answer properly
2. Think carefully if you really want to do that. It avoids to mix up 2 tickers. Quite a few functions from quantmod and xts will still work if the ticker name is part of the column name. Maybe you should follow the same convention? You can check the code of quantmod::Cl to see how it is done.

Upvotes: 1

Related Questions