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
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
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
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.