NIrbhay Mathur
NIrbhay Mathur

Reputation: 196

Convert chr to time format using chorn

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.

Upvotes: 0

Views: 137

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

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))

Upvotes: 1

Related Questions