简体   繁体   中英

Convert Factor variable to date

I have a vector which has date embedded in it but has data type Factor .

Example

time  
[1] Jan-14 Feb-14 Mar-14 Apr-14  
Levels: Apr-14 Feb-14 Jan-14 Mar-14

I would like to separate year and month from this using R. Other similar questions had the correct format of date ie YMD, so on.. Can anyone suggest any idea?

I tried using strsplit() . It seperates the date like this

time<-strsplit(x = as.character(time), split = "-")  
time  
[[1]]  
[1] "Jan" "14"   
[[2]]  
[1] "Feb" "14"   
[[3]]  
[1] "Mar" "14"  
[[4]]  
[1] "Apr" "14" 

How do I save these month and year in new column?

We can paste with a day number and use as.Date

as.Date(paste0(time,"-01"), "%b-%y-%d")
#[1] "2014-01-01" "2014-02-01" "2014-03-01" "2014-04-01"

If we need to separate to two columns

read.table(text=as.character(time), sep="-", col.names = c("Month", "Year"))
#   Month Year
#1   Jan   14
#2   Feb   14
#3   Mar   14
#4   Apr   14

data

time <- factor(c("Jan-14", "Feb-14", "Mar-14", "Apr-14"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM