Calculate difference between dates in days on the R

Asked

Viewed 3,255 times

3

How do I calculate the difference between dates and have the result in days?

I have a column in my table called input with data similar to the ones shown below:

Entree

2017-01-27
2017-06-01
2017-10-05
2017-09-27
2017-08-31
2017-04-02
2017-03-30
2017-07-01
2017-07-27
2017-10-24
2017-02-23
2017-02-10
2017-05-26
...

I tried to calculate the difference by the specific date of day 2018-01-01 (standard date for all calculation) using the function:

entrada["atualização"] <- difftime((entrada), 2018-01-01, units = c("days"))

And I had an answer

Error in as.POSIXct.default(time1) : 
  do not know how to convert 'time1' to class “POSIXct

Can someone give me a help on how to solve this problem or another way to calculate the difference between these dates?

1 answer

3


First of all, I’m not sure what the names of your data are, I’ll call the data frame time1 and to your column entrada. If this isn’t right, say you just change the names, the code is still good.

Second, see what you wrote in the instruction difftime:

difftime((entrada), 2018-01-01, units = c("days"))

This 2018-01-01 is not a date is a subtraction of three numbers! Try running this on the command line and see what you get. Also, parentheses in (entrada) nor the function c() in c("days"). It’s not that it’s wrong, it’s just not necessary(*).

Now the code. To apply the difftime both dates must be or inherit from class Date or POSIXt (for example POSIXct or POSIXlt). So we use the function as.Date in the whole column and the base date 2018-01-01.

time1$entrada <- as.Date(time1$entrada)

time1[["atualização"]] <- difftime(time1$entrada, as.Date("2018-01-01"), units = "days")

time1
#      entrada atualização
#1  2017-01-27   -339 days
#2  2017-06-01   -214 days
#3  2017-10-05    -88 days
#4  2017-09-27    -96 days
#5  2017-08-31   -123 days
#6  2017-04-02   -274 days
#7  2017-03-30   -277 days
#8  2017-07-01   -184 days
#9  2017-07-27   -158 days
#10 2017-10-24    -69 days
#11 2017-02-23   -312 days
#12 2017-02-10   -325 days
#13 2017-05-26   -220 days

DICE

dput(time1)
structure(list(entrada = c("2017-01-27", "2017-06-01", "2017-10-05", 
"2017-09-27", "2017-08-31", "2017-04-02", "2017-03-30", "2017-07-01", 
"2017-07-27", "2017-10-24", "2017-02-23", "2017-02-10", "2017-05-26"
)), .Names = "entrada", class = "data.frame", row.names = c(NA, 
-13L))

(*) The function c() is required to create vectors with more than one element, c("days") only one element. For example, c("a", "b") already has more than one element.

  • It worked perfectly, but is it possible to display the result without the sign of - in front of days? Or is there a command I can use to take out the signal?

  • 1

    @dflagher There is there, but the sign has meaning. For the absolute value of the difference, just do abs(difftime(etc)).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.