I have a df with a column datetime (DD:MM:yyyy HH:mm:ss)named "Start" and I would like to split this column into two named "date" and "time".
Now I have tried the following:
df$Date <- sapply(strsplit(as.character(df$Start), " "), "[", 1)
df$Time <- sapply(strsplit(as.character(df$Start), " "), "[", 2)
This works, however, if I use the function str(df) (I cut it short so you can mostly see the variables of my concern).
'data.frame': 18363 obs. of 19 variables:
$ Start : Factor w/ 67 levels "2013-09-01 08:07:41.000",..: 1 1 1 1 1 1 1 1 1 1 ...
$ Interval : int 47259 47259 47259 47259 47259 47259 47259 47259 47259 47259 ...
$ DateTime : Factor w/ 18363 levels "2013-09-01 08:07:41.350",..: 1 2 3 4 5 6 7 8 9 10 ...
$ TimeSensor: num 158489 158489 158490 158490 158491 ...
So now I only need to know how to convert the time and date from 'factors' to 'time' and 'date'.
If someone knows the solution I would be very grateful! I am a noob concerning R so please do not burn me to the ground..
Thanks a million!
Sorry for this late answer! Anyways, I got help from someone at the university and he came up with the following, very simple, adjustment of my time-code..:
This converts the factors to "date" and "POSIXct", just how I wanted it.
Thank all of you for your help! I hope I can return some kind of favour in the future, although I doubt if it will be with programming..!
You might prefer to do something like this, avoiding the use of an
lapply
loop which isn't really necessary (but it's not a bad thing either!)...By seeing your column format, I'd say you could use as.POSIXct to properly format your column, and then use format() to extract the desired data.
This is the code I use when splitting a DateTime column,
How about
You can use it in this method. It works very good
Hope it helps!
Assuming your data looks similar to this with one
datetime
column and many other columnsWe can split the column on whitespace (or any other delimiter present) to get a separate date and time columns which can be done using
tidyr::separate
If we want to keep the original column (
datetime
) we can addremove = FALSE
.