0

I am trying to transform my date dataset from chr to time format.

Here is my code :

time<-f1%>%
  mutate(`ymd_hms(Timestamp)`=strftime(f1$`ymd_hms(Timestamp)`, tz="GMT", format = "%H:%M:%S"))%>%
  transform(as.numeric(f1$SpotPrice))
  chron(times=f1$`ymd_hms(Timestamp)`)

its showing error:

Error in chron(., times = f1$`ymd_hms(Timestamp)`) : 
  . and f1$`ymd_hms(Timestamp)` must have equal lengths

if i comment it

time<-f1%>%
  mutate(`ymd_hms(Timestamp)`=strftime(f1$`ymd_hms(Timestamp)`, tz="GMT", format = "%H:%M:%S"))%>%
  transform(as.numeric(f1$SpotPrice))
#chron(times=f1$`ymd_hms(Timestamp)`)

output is

'data.frame':   10078 obs. of  4 variables:
 $ InstanceType      : chr  "  a1.2xlarge" "  a1.2xlarge" "  a1.2xlarge" "  a1.4xlarge" ...
 $ ProductDescription: chr  "  Linux/UNIX" "  Red Hat Enterprise Linux" "  SUSE Linux" "  Linux/UNIX" ...
 $ SpotPrice         : num  0.0671 0.1971 0.2171 0.1343 0.2643 ...
 $ ymd_hms(Timestamp): chr  "06:17:23" "06:17:23" "06:17:23" "12:15:54" ...

Also but i use this commend as a single variable as follows:

f2<-chron(times=DfUse$`ymd_hms(Timestamp)`)

it works and shows the output

 'times' num [1:10078] 06:17:23 06:17:23 06:17:23 12:15:54 12:15:54 ...
 - attr(*, "format")= chr "h:m:s"`

but i want to pipe it with my whole dataset not to use it alone as a single variable.

Thanks in advance.

NIrbhay Mathur
  • 153
  • 1
  • 1
  • 10

1 Answers1

1

There are few syntax errors and room for improvement in the code.

  • Although having ymd_hms(Timestamp) = on the left hand side works but you don't need that since it creates a column with that name. Only using Timestamp should be good.

  • Don't use $ in dplyr pipe.

  • Usually it is better to keep base R functions and dplyr functions separate. transform is in base R but you can use the same mutate pipe to turn SpotPrice to numeric.

library(dplyr)

time<-f1%>%
  mutate(Timestamp = strftime(ymd_hms(Timestamp), tz="GMT", format = "%H:%M:%S"),
         SpotPrice = as.numeric(SpotPrice),
         Timestamp = chron::chron(times=Timestamp))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks, @Ronak for your reply. But now when i use line plot using ggplot2 -x axis dint show the time scale. – NIrbhay Mathur Jul 12 '21 at 13:33
  • I have not used `chron` data type for plotting, I usually use `POSIXct` for it. You may want to ask a new question related to plotting code. – Ronak Shah Jul 12 '21 at 13:40
  • ggplot(data=DfFilter, aes(x=Timestamp, y=SpotPrice))+ geom_line()+ #scale_x_datetime(labels = Timestamp) scale_x_continuous(expand = c(0,0)) – NIrbhay Mathur Jul 12 '21 at 13:41