Hi.
I have a data frame where date is mentioned in character, how can convert it to date format.
typeof(phen1$DATE)
[1] "character"
date format is (10/25/2013) i also want this to change to (25/10/2013) format.
i have one more date column that is also in character type.
format looks like ( 10/31/13 7:13 ) i want to change this also to date type.
My data data contains time column as well, which is in character type.
format looks like (18:15) , i want to change this to time type.( 24 hrs time format ) .
library(lubridate)
library(tidyverse)
library(hms)
time <- c("8H 0m 0s", " 18H 6M 0S", " 16H 30M 0S")
ID <- c(1,2,3)
df <- data.frame(ID,time)
#exctracting the numbers
df2 <- regmatches(time, gregexpr("[[:digit:]]+", time)) %>% unlist() %>% as.numeric()
#taking the vector and converting it into a matrix and then dataframe
df3 <- matrix(df2,ncol = 3) %>% t() %>% as.data.frame()
#giving it some proper names and binding it with the original
names(df3) <- c("h","m","s")
df3 <- cbind(df,df3)
#creating the new variable where we take the number of hours and minutes and express it as total number of seconds
df4 <- df3 %>% mutate(time2 = hms::as_hms((h*60*60)+(m*60)))
df4
#> ID time h m s time2
#> 1 1 8H 0m 0s 8 0 0 08:00:00
#> 2 2 18H 6M 0S 18 6 0 18:06:00
#> 3 3 16H 30M 0S 16 30 0 16:30:00
Just note that you will have to change ncol = 3 if you have a much larger file (base it on the length of ID. There might be an easier way to accomplish this but seems to work relatively well (I didn't clean up all the steps).