Kalyan Pavan
Kalyan Pavan

Reputation: 45

Format change when list is given as column names

I have created list of intervals from below code.

library(lubridate)    
date1 <- ymd_hms("2000-01-01 05:30:00",tz = "US/Eastern")  
shifts <- lapply(0:14, function(x){
  mapply(function(y,z){
    interval((date1+days(x)+minutes(y)), (date1+days(x)+minutes(y+z)))
  }, y = c(0,150,390,570,690,810,1050), z = c(600,570,600,600,600,600,600), SIMPLIFY = FALSE)
})

I have another data set df with 105 columns.

I am trying to give column names as shifts intervals.

But the format is changing. I want my column names as same as shifts. I am trying as below.

list <- unlist(shifts, recursive = FALSE)

colnames(df)<-as.date(list)

Upvotes: 0

Views: 35

Answers (1)

snair.stack
snair.stack

Reputation: 415

The reason this is failing is because list is still of type interval. If you want to use the contents of this interval as colnames, you need to convert them to a list of characters like this:

list <- unlist(shifts, recursive = FALSE)
dmy <- list()
for(i in 1:length(list)){
    foo <- c(list[[i]])
    foo <- as.character(foo)
    dmy <- append(dmy, foo)
}
colnames(df) <- dmy # list of characters

Output:

> class(list[[1]])
[1] "Interval"
attr(,"package")
[1] "lubridate"
> class(dmy[[1]])
[1] "character"

Now you should be able to rename columns of df :)

Upvotes: 1

Related Questions