【发布时间】:2023-04-08 22:44:01
【问题描述】:
我有一些看起来有点像这样的数据:
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"
我只想要年份和月份。我不需要那一天,所以我不担心最后一天无效。不幸的是,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
我知道通常的答案是修复日期的日期部分,例如使用paste(x, '01', sep='')。我认为这在这里行不通,因为我事先不知道日期格式是什么,因此如果不先转换为某种日期对象,我就无法设置日期。
【问题讨论】:
-
as.yearmon在什么包中?代码应该是可重现的。此外,您还在示例数据中强制使用整数来表示字符,所以这并不理想。 -
@mdsumner:
as.yearmon在 zoo 包中。 -
我知道,但它应该在 q 中——我现在看到了
-
您需要更清楚 "get the year and month" 是否意味着 作为字符串,或某种日期类型,或任何东西 ?似乎您的意思是作为某种数据类型(在本例中为 zoo::yearmon)。你能编辑你的标题清楚吗? (我不知道你想要什么,否则我会自己编辑)