我有一些看起来像这样的数据:
require(zoo)
X <- rbind(c(date='20111001', fmt='%Y%m%d'),
c('20111031', '%Y%m%d'),
c('201110', '%Y%m'),
c('102011', '%m%Y'),
c('31/10/2011', '%d/%m/%Y'),
c('20111000', '%Y%m%d'))
print(X)
# date fmt
# [1,] "20111001" "%Y%m%d"
# [2,] "20111031" "%Y%m%d"
# [3,] "201110" "%Y%m"
# [4,] "102011" "%m%Y"
# [5,] "31/10/2011" "%d/%m/%Y"
# [6,] "20111000" "%Y%m%d"
Run Code Online (Sandbox Code Playgroud)
我只想要年月.我不需要这一天,所以我不担心最后一天是无效的.不幸的是,R是:
mapply(as.yearmon, X[, 'date'], X[, 'fmt'], SIMPLIFY=FALSE)
# $`20111001`
# [1] "Oct 2011"
# $`20111031`
# [1] "Oct 2011"
# $`201110`
# [1] "Oct 2011"
# $`102011`
# [1] "Oct 2011"
# $`31/10/2011`
# [1] "Oct 2011"
# $`20111000`
# Error in charToDate(x) :
# character string is not in a standard unambiguous format
Run Code Online (Sandbox Code Playgroud)
我知道通常的答案是确定日期的一部分,例如使用paste(x, '01', sep='').我认为这不会起作用,因为我事先并不知道日期格式是什么,因此我无法设置日期而不先转换为某种日期对象.
假设月份总是在年份之后,并且总是两个字符date.为什么不直接提取信息substr.也许是这样的:
lapply(X[,'date'],
function(x) paste(month.abb[as.numeric(substr(x, 5, 6))], substr(x, 1, 4))
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
276 次 |
| 最近记录: |