-3

I am trying to convert the variable below from a factor with 542 levels to a Date which is recognised by R as numeric. I am very new to R and was unable to follow the explanations in other threads.

Thanks a lot! Sara

screen shot of data

Sara Correia
  • 45
  • 1
  • 6
  • 1
    share data please instead of sharing the screenshot – mtoto Jan 15 '16 at 12:10
  • 1
    This maybe helps: http://stackoverflow.com/questions/18160732/factor-as-date-to-numeric – Jaap Jan 15 '16 at 12:16
  • 2
    Furthermore: Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Jan 15 '16 at 12:16
  • Thanks for your suggestions, I shall take that on board in the future. – Sara Correia Jan 18 '16 at 14:49

2 Answers2

0

Assuming you're after ISO8601 YYYYMMDD formated numbers, how about this?

dates <- c("18/08/2015","19/08/2015")
dateNumbers <- as.numeric(as.character(as.Date(dates, format = "%d/%m/%Y"), format="%Y%m%d"))
dateNumbers
[1] 20150818 20150819
Liesel
  • 2,809
  • 2
  • 9
  • 16
-1

Your screenshot looks like a vector. So try this:

lapply(some_vec, function(date) gsub('-', '', date) )

EDIT: May be you need to reformat the date with:

some_vec <- as.Date(some_vec, format = '%Y-%m-%d')

before.

EDIT2:

First the code:

some_vec <- rep(factor(as.Date('18/08/2015', format = '%d/%m/%Y')), 30)
some_vec <- as.Date(some_vec, format = '%Y-%m-%d')
res <- unlist(lapply(some_vec, function(date) { 
   gsub('-', '', date)
}))
res
[1] "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818"
[15] "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818" "20150818"
[29] "20150818" "20150818"

I tried to help blindfolded here. So, please don't be harsh. What I tried is to reformat the date (if even necessary). On my System R shows the date already in the 'YYYY-MM-DD' format (before the reformating).

some_vec
[1] 2015-08-18 2015-08-18 2015-08-18 2015-08-18 2015-08-18 2015-08-18 ...
[29] 2015-08-18 2015-08-18
Levels: 2015-08-18

Once the data has this format you can lapply over the list and kill the '-' signs.

Robert Kirsten
  • 444
  • 2
  • 5
  • 12