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?
– dflagher
@dflagher There is there, but the sign has meaning. For the absolute value of the difference, just do
abs(difftime(etc))
.– Rui Barradas