Home > database >  Changing column name - replace the prefix
Changing column name - replace the prefix

Time:10-21

Suppose I have the dataframe below:

>colnames(df)

>[1] "0939.HK.Open"     "0939.HK.High"     "0939.HK.Low"      "0939.HK.Close"    "0939.HK.Volume"   "0939.HK.Adjusted"

Wondering if I can replace column name with a defined symbol?

>symbol<-'0123.KI' 

And what I would like to obtain is:

>[1] "0123.KI.Open" "0123.KI.High" "0123.KI.Low" "0123.KI.Close" "0123.KI.Volume" "0123.KI.Adjusted"

Thank you so much guys.

CodePudding user response:

Try:

colnames(df) <- paste0(symbol, ".", tools::file_ext(colnames(df)))

As the column names look like a filename, I am taking the extension - file_ext, then adding the symbol using paste0.

CodePudding user response:

Another way:

symbol <- '0123.KI'
colnames(df) <- gsub("0939.HK", symbol, colnames(df), fixed=TRUE)
  • Related