2

I have a R data frame like bellow,

Time      value
00:00:00      1
00:00:03      3
00:00:06      2
00:00:09      1

When I check the classes of fields in dataframe, i found that,

    Time     value
"factor" "integer"  

Then I try to convert Time's data type into time using bellow code.

df["Time"] <- as.POSIXct(df["Time"],format="%H:%M:%S")

When I execute above code below error was generated.

Error in as.POSIXct.default(df["Time"], format = "%H:%M:%S") : do not know how to convert 'df["Time"]' to class “POSIXct”

My questions are, why is this error occurred and how I can over come this?

Adam Bethke
  • 1,028
  • 2
  • 19
  • 35
GihanDB
  • 591
  • 2
  • 6
  • 23

2 Answers2

1

The reason that fails is because of the way you call the column Time. The easiest way to do it is to use the $, i.e.

as.POSIXct(df$Time,format="%H:%M:%S")

If however, you want to use brackets then you need to add 2 of them in order to extract it as a vector rather than as a data frame column, i.e.

as.POSIXct(df[["Time"]],format="%H:%M:%S")

Both of the above result to,

[1] "2017-11-23 00:00:00 +03" "2017-11-23 00:00:03 +03" "2017-11-23 00:00:06 +03" "2017-11-23 00:00:09 +03"
Sotos
  • 51,121
  • 6
  • 32
  • 66
0

Does this work:

df["Time"] <- as.POSIXct(as.character(df["Time"]),format="%H:%M:%S")
Dhiraj
  • 1,650
  • 1
  • 18
  • 44