简体   繁体   中英

Factor to Month-Year Conversion in R

Have a factor column as April-2017 February-2017 etc. Want to convert it to Month and Year to order the column as per the month and year so that it start from January. Tried following:

Combi$Month <- as.yearmon(levels(Combined$Month))[Combined$Month] -> Yields 'NA'
Combined$Month <- as.Date(Combined$Month,'%B-%Y') -> Yields 'NA'

The "yearmon" class can represent year-month and sorts as expected:

library(zoo)
x <- factor(c('April-2017', 'February-2017')) # test data

ym <- as.yearmon(x, "%B-%Y")
sort(ym)
## [1] "Feb 2017" "Apr 2017"

Because of this you don't really need to convert it to "Date" class nor do you need the year and month separately but if for some reason not stated in the question you still do need separate values then as.integer(ym) and cycle(ym) give the years as 4 digit numbers and the months as numbers between 1 and 12. Also as.Date(ym) gives "Date" class values.

An R base way:

# Some sample data
df <- data.frame(period=sample(c("April-2017","February-2017"),10, replace = TRUE))

nicep <- function(x) {
    months <- c('January','February','March','April','May','June','July','August','September','October','November','December')
    l <- strsplit(x, '-')
    return(sprintf("%s-%02d",l[[1]][2], which(months == l[[1]][1])))
}

# change levels for a nice name
levels(df$period) <- unlist(lapply(as.character(levels(df$period)), FUN=nicep))

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