I am stuck combining two columns of a data frame into one. Below is the code to reproduce the problem
df <- data.frame(date = c("2/13/1962 0:00:00", "4/13/1972 0:00:00", "3/13/1982 0:00:00", "12/13/1992 0:00:00"),
time = c("0900", "1000", "1101", "1603"))
#This works
df$tmp <- as.Date(df$date, format="%m/%d/%Y")
df
date time tmp
1 2/13/1962 0:00:00 0900 1962-02-13
2 4/13/1972 0:00:00 1000 1972-04-13
3 3/13/1982 0:00:00 1101 1982-03-13
4 12/13/1992 0:00:00 1603 1992-12-13
# this doesn't
df$tmp <- strptime(strsplit(as.character(df$date), " ")[[1]][1], format="%m/%d/%Y")
df
1 2/13/1962 0:00:00 0900 1962-02-13
2 4/13/1972 0:00:00 1000 1962-02-13
3 3/13/1982 0:00:00 1101 1962-02-13
4 12/13/1992 0:00:00 1603 1962-02-13
I would like to end up with a column that combines the date part of the date and the time column but was unable to get to this result.
While experimenting I noticed that the as.Date
function does convert the date . On the other hand, with the strsplit
function all rows end up with the first date.
I would greatly appreciate any help towards a solution, ending up with 4 rows have a "Date" object:
1 1962-02-13 09:00
2 1972-04-13 10:00
3 1982-03-13 11:01
4 1992-12-13 16:03
You may paste
the date and time variable, and then use as.POSIXct
with appropriate format
:
as.POSIXct(x = paste(as.Date(df$date, format = "%m/%d/%Y"), df$time),
format = "%Y-%m-%d %H%M")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.