I am using the R programming language. I am trying to take the difference between two date columns. Both dates are in the following format : 2010-01-01 12:01
When I bring my file into R, the dates are in "Factor" format. Here is my attempt to recreate the file in R:
#how my file looks like when I import it into R
date_1 = c("2010-01-01 13:01 ", "2010-01-01 14:01" )
date_2 = c("2010-01-01 15:01 ", "2010-01-01 16:01" )
file = data.frame(date_1, date_2)
file$date_1 = as.factor(file$date_1)
file$date_2 = as.factor(file$date_2)
Now, I am trying to create a new column which takes the difference between these dates (in minutes)
I first tried to convert both date variables into the appropriate "Date" formats:
#convert to date formats:
file$date_a = as.POSIXlt(file$date_1,format="%Y-%m-%dT%H:%M")
file$date_b = as.POSIXlt(file$date_2,format="%Y-%m-%dT%H:%M")
Then, I tried to take the difference :
file$diff = difftime(file$date_a, file$date_b, units="mins")
But this results in "NA's":
> file
date_1 date_2 date_a date_b diff
1 2010-01-01 13:01 2010-01-01 13:01 <NA> <NA> NA mins
2 2010-01-01 13:01 2010-01-01 13:01 <NA> <NA> NA mins
Can someone please show me what I am doing wrong?
Thanks
Reference: How to get difference (in minutes) between two date strings?