Calculate difference between dates in days in R

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:

Entry

  

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 (default date for the entire calculation) using the function:

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

And I had the answer

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

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

    
asked by anonymous 31.01.2018 / 07:54

1 answer

2

First, I'm not sure what your data names are, I'll call the frame time1 and its entrada column. If this is not right say that you just change the names, the code continues to run smoothly.

Second, see what you wrote in the difftime statement:

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 it does. In addition, parentheses are not required in (entrada) nor the c() function in c("days") . It is not that it gives an error, it simply is not necessary (*).

Now the code. To apply difftime both dates must be or inherit from class Date or POSIXt (for example POSIXct or POSIXlt ). So we use the as.Date function in the entire 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

DATA

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 c() function is required to create vectors with more than one element, c("days") has only one element. For example, c("a", "b") already has more than one element.

    
31.01.2018 / 12:46