Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I am having the following dataframe:

structure(list(time = structure(c(1177345800, 1177408800, 1177410600, 

1177412400, 1177414200), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 

    open = c(148.09, 148.23, 148.03, 147.48, 147.51), high = c(148.12, 

    148.29, 148.04, 147.65, 147.78), low = c(148.05, 147.85, 

    147.38, 147.32, 147.43), close = c(148.06, 148.04, 147.48, 

    147.51, 147.77), volume = c(172700L, 8306934L, 21686377L, 

    10742987L, 6065554L)), row.names = c(NA, -5L), class = c("data.table", 

"data.frame"), .internal.selfref = <pointer: 0x000001a7a5941ef0>)

As you can observe that the date and the time are unified in one column. I would like to separate them into two columns.

And also I want to transform the time format: from "16:30:00" to "16:30". I want to eliminate that last ":00" for all the rows.

1 Answer

0 votes
by (108k points)

From your data.table you can use the data.table package to achieve your desired output in R programming:

library(data.table)

df[, c('date', 'time') := list(as.Date(time), format(time, '%H:%M'))]

df

#    time   open   high    low  close   volume       date

#1: 16:30 148.09 148.12 148.05 148.06   172700 2007-04-23

#2: 10:00 148.23 148.29 147.85 148.04  8306934 2007-04-24

#3: 10:30 148.03 148.04 147.38 147.48 21686377 2007-04-24

#4: 11:00 147.48 147.65 147.32 147.51 10742987 2007-04-24

#5: 11:30 147.51 147.78 147.43 147.77  6065554 2007-04-24

Browse Categories

...