Jalalala
Jalalala

Reputation: 727

Convert factor to time in R

I have a small problem which I cannot seem to figure out. I have searched several topics and websites to find a solution, and I have tried numerous different things but nothing seems to work..
I have a dataset with two columns, one for date and one for time:

$ StartDate : Date, format: "2013-09-01" "2013-09-01" "2013-09-01" "2013-09-01" ...
$ StartTime : Factor w/ 43 levels "00:02:43","00:07:05",..:

As you can see, I already converted the column "StartDate to "Date" and I would like to convert the column StartTime to "POSIXct".. I had a big dataset which I splitted, in this big dataset I had the variables date and time set right. I used the following loop to split the file:

for  (Cow in unique(df$CowID)){   #loop through each level of CowID
  df <- RawData[df$CowID == Cow,]      #extract all rows where CowID equals Cow
  write.csv(df, paste("CowID_",Cow,".csv",sep = ""),row.names = F)}    #write new dataframe to .csv

Should I have used an extra piece of code to keep the variables? After using this loop I got 68 different .csv files which I then separately read into R by using the next code:

C292 <- read.csv(file = "C:\\...\\CowID_12292.csv",
     header = T, skip = 0, colClasses = c("StartDate" = "Date", "Date" = "Date", 
     "StartTime" = "character", "Time" = "character"))

Ofcourse, now these variables for time are "chr". I have no clue how to convert this.. Can anyone help me? I tried as.POSIXct() but that did not seem to work, I only NA in the column..

Thanks in advance!

ADD > dput(head(C292))

structure(list(CowID = c(12292L, 12292L, 12292L, 12292L, 12292L, 12292L), StartDate = structure(c(15949, 15949, 15949, 15949, 15949, 15949), class = "Date"), StartTime = c("02:16:16", "02:16:16", "02:16:16", "02:16:16", "02:16:16", "02:16:16")

Do I really need to add the date into the column time? Or is there also a way to leave it out, but still keep the variable POSIXct? I would like to split the file by date and then plot the days on a timeline of 24hours. I do not know if this is even possible, I am quite a noob in R. However, it is a very clever program so I guess it is possible. Just have to figure out a way to do it!

Upvotes: 1

Views: 6341

Answers (1)

Sophia
Sophia

Reputation: 1951

You need to include the date to use as.POSIXct() with a time. Try this:

as.POSIXct(paste(C292$StartDate, as.character(C292$StartTime)))

Upvotes: 1

Related Questions