将月份缩写转换为数字月份,在R中 [英] Convert a month abbreviation to a numeric month, in R

查看:477
本文介绍了将月份缩写转换为数字月份,在R中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在尝试编写一个函数,将3个字母的月份缩写转换为R中的数字值。我想知道是否有更好的方法:

  numMonth<  -  function(x){
months< - list = 1,feb = 2,mar = 3,apr = 4,may = 5,jun = 6,jul = 7,aug = 8,sep = 9,oct = 10,nov = 11,dec = 12)
x< - tolower(x)
sapply(x,function(x)months [[x]])
}

numMonth(c('JAN','DEC '))


解决方案

由于month.abb是系统常量,为什么不使用:

  match(jan,tolower(month.abb))
#[1] 1

mo2Num< - function(x)match(tolower(x),tolower(month.abb))
mo2Num(c(jan,JAN ,垃圾))
#[1] 1 1 2 NA

如果你想要查看其余的系统常量的数量相对较少,请转到

 `?Constants` 

示例文本意味着这些应该在与您的区域设置相关联的语言中(尽管我无法以权限的方式说出将是哪一种语言环境。替代方法可能是在转换为POSIXlt对象后提取月份号a。这种方法需要记住月份号为0的,所以你需要在这个例子中添加1。


I'm trying to write a function to convert 3-letter month abreviations to numeric values in R.

Here's what I have, I was wondering if there's a better way to do this:

numMonth <- function(x) {
    months <- list(jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12)
    x <- tolower(x)
    sapply(x,function(x) months[[x]])
}

numMonth(c('JAN','DEC'))

解决方案

Since month.abb is a system constant, why not use:

 match("jan", tolower(month.abb))
 # [1] 1

 mo2Num <- function(x) match(tolower(x), tolower(month.abb))
 mo2Num(c("jan", "JAN", "Feb", "junk")  )
 #[1]  1  1  2 NA

If you want to see the rest of the relatively small number of "system constants", go to

`?Constants`

The example text implies these should be in the language associated with your locale (although I'm not able to say with authority which of locales that would be. An alternate approach might have been to extract the month numbera after conversion to a POSIXlt-object. This approach requires remembering that the month number os 0-based, so you would need to add 1 in this instance.

这篇关于将月份缩写转换为数字月份,在R中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆