0

I want to change all of the dates 2006-04-11 in my dataset to 2006-04-01. I converted the date variable to a factor, recoded 2006-04-11 to 2006-04-01, and re-converted the variable back to class = date.

The recode works while the variable is a factor (all 2006-04-11 dates are changed to 2006-04-01), but after converting back to class = date, the variables once again appear as 2006-04-11.

Convert date variable to factor and check it worked.

data$review_date<-as.factor(data$review_date)
class(data$review_date)

Recode factor variable to the date I want (2006-04-01) and view data.

recode_factor(data$review_date, '2006-04-11' = "2006-04-01")
data$review_date

Convert variable from factor back to date, check class, and view data.

data$review_date <- as_date(data$review_date,"%y/%m/%d")
class(review_date)
str(data)
data$review_date

Alternatively, I would be willing to drop the day part of all dates entirely, but I have not figured out how to do that.

nusbaume
  • 27
  • 1
  • 1
  • 6
  • As to the last line about dropping days altogether - see `yearmon` from the `zoo` package which stores year/month date objects. – thelatemail Nov 10 '16 at 00:29

1 Answers1

3

recode_factor() doesn't update the values in data. You have to assign the results back again like:

data$review_date <- recode_factor(data$review_date, '2006-04-11' = "2006-04-01")

...so it can overwrite the original values.

The whole process can just be a simple replace operation too. E.g.:

data <- data.frame(review_date = as.Date(c("2006-04-11","2001-01-01")))
data$review_date[data$review_date == "2006-04-11"] <- "2006-04-01" 

(yes, this will give an appropriate Date class variable)

thelatemail
  • 91,185
  • 12
  • 128
  • 188