I am trying to create a new calculated field,
mutate(df, length_of_time = 10/23/2016 - final_date)
"Error in eval(substitute(expr), envir, enclos) :
can only subtract from "POSIXt" objects"
df <- as.POSIXlt(df$final_date)
Error in UseMethod("mutate_") :
no applicable method for 'mutate_' applied to an object of class "c('POSIXlt', 'POSIXt')"
You've got your date formats a bit confused. (see code comments for explanation)
library(dplyr) df <- data.frame(final_date = c("2/10/2016","4/4/2016")) ## you need to specify the format of your date columns as it is ambiguous ## I've guessed you're using day/month/year df$final_date <- as.POSIXct(df$final_date, format = "%d/%m/%Y") ## and you need to subtract the `final_date` (which is POSIXct) ## from another POSIXct object mutate(df, length_of_time = as.POSIXct("2016-10-23") - final_date) final_date length_of_time 1 2016-10-02 20.95833 days 2 2016-04-04 201.95833 days
I recommend reading the documentation on dates & times to also understand the difference between
POSIXlt, date formats, date calculations etc.