Search code examples
rnames

Adding name to the first column in r


my dataset is missing name for the first column (there are dates in it)

I tried colnames(managers)[1] <- "date" but it renamed the second column

> #load data
> data(managers) 
> colnames(managers)[1] <- "date"
> View(head(managers,10))
> str(managers)
An ‘xts’ object on 1996-01-31/2006-12-31 containing:
  Data: num [1:132, 1:10] 0.0074 0.0193 0.0155 -0.0091 0.0076 -0.0039 -0.0231 0.0395 0.0147 0.0288 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:10] "date" "HAM2" "HAM3" "HAM4" ...
  Indexed by objects of class: [Date] TZ: UTC
  xts Attributes:  
 NULL

dataset headers


Solution

  • The 'managers' is an xts object and the dates are the index

    library(PerformanceAnalytics)
    index(managers)
    #[1] "1996-01-31" "1996-02-29" "1996-03-31" "1996-04-30" "1996-05-31" "1996-06-30" ...
    

    The columns of the dataset are

    colnames(managers)
    #[1] "HAM1"        "HAM2"        "HAM3"        "HAM4"        "HAM5"        "HAM6"        "EDHEC LS EQ" "SP500 TR"    "US 10Y TR"   "US 3m TR"  
    

    If we want to convert it to data.frame, then use fortify.zoo

    library(zoo)
    managers1 <- fortify.zoo(managers)
    colnames(managers)[1] <- 'date'
    

    Or specify the names in fortify.zoo

    managers1 <- fortify.zoo(managers, names = "date")