Betty
Betty

Reputation: 183

Using R to convert factor to date

I know this question has been asked repeatedly, apologies, but I just can't see the error... Trying to convert a factor to a date as below and no matter what I've tried I still get N/A.

> class(cd$StartDate)
[1] "factor"
> head(cd)
  StartDate      Phase Cancer
1   Dec-89   Phase  2  breast
2   Jul-89   Phase  2  breast
3   Sep-92   Phase  1  breast

> cd$dates <- as.Date(cd$StartDate, format = "%b-%y)

> head(cd)
  StartDate      Phase Cancer dates
1   Dec-89   Phase  2  breast  <NA>
2   Jul-89   Phase  2  breast  <NA>
3   Sep-92   Phase  1  breast  <NA>

Upvotes: 1

Views: 4333

Answers (2)

Abhishek Mathpal
Abhishek Mathpal

Reputation: 1

I also tried:

as.Date(as.character(cd$StartDate),format = "%m/%d/%y")

but below one works

 a<-as.character(cd$StartDate)
 b<-as.Date.character(a, format = "%m/%d/%Y")
 b

The Y in capitals in the format makes the difference.

Upvotes: 0

nrussell
nrussell

Reputation: 18602

I think you need to supply a day value for the conversion to work:

cd$dates <- as.Date(
  paste0(as.character(cd$StartDate), "-01"), 
  format = "%b-%y-%d")
##
R> str(cd)
#'data.frame':  3 obs. of  4 variables:
#$ StartDate: Factor w/ 3 levels "Dec-89","Jul-89",..: 1 2 3
#$ Phase    : chr  "Phase_2" "Phase_2" "Phase_1"
#$ Cancer   : chr  "breast" "breast" "breast"
#$ dates    : Date, format: "1989-12-01" "1989-07-01" "1992-09-01"

Data:

cd <- read.table(
  text = "  StartDate      Phase Cancer
1   Dec-89   Phase_2  breast
2   Jul-89   Phase_2  breast
3   Sep-92   Phase_1  breast",
  header = TRUE,
  stringsAsFactors = FALSE)
##
cd$StartDate <- as.factor(cd$StartDate)

Upvotes: 3

Related Questions