mapply 将日期更改为双倍

mapply changes dates to double

如何防止 mapply 将日期更改为双倍日期?

这就是我的意思:

datedf<-data.frame(y=as.character(rep(2010,12)),m=as.character(seq(1,12,1)),stringsAsFactors=FALSE)
head(datedf)

yyyymm_to_date<-function(y,m) {
  return(as.Date(paste0(y,ifelse(nchar(m)==1,paste0("0",m),m),"01"),"%Y%m%d"))
}    

yyyymm_to_date("2000","4") # prints "2010-04-01"

datedf$d<-mapply(FUN=yyyymm_to_date,y=datedf$y,m=datedf$m,SIMPLIFY=FALSE) # simplify does not help
head(datedf) # prints double numbers ?? --> want dates

谢谢&亲切的问候

一行而不是所有这个函数调用。

as.Date(with(datedf, paste(y, sprintf("%02d", as.numeric(m)), "01", sep = "-")))

# "2010-01-01" "2010-02-01" "2010-03-01" "2010-04-01" "2010-05-01" 
# "2010-06-01" "2010-07-01" "2010-08-01" "2010-09-01" "2010-10-01" 
# "2010-11-01" "2010-12-01"

检查class

a <- as.Date(with(datedf, paste(y,sprintf("%02d", as.numeric(m)),"01",sep = "-"))))
class(a)
#[1] "Date"

我们 paste 01 到年 (y) 和月 (m) 的每个组合,然后通过 as.Date 将其转换为日期。

你只需要一个do.call(因为mapply returns一个list),你的代码完全没问题:

datedf$d <- do.call('c',mapply(FUN=yyyymm_to_date,y=datedf$y,m=datedf$m,SIMPLIFY=FALSE))
head(datedf)
#     y m          d
#1 2010 1 2010-01-01
#2 2010 2 2010-02-01
#3 2010 3 2010-03-01
#4 2010 4 2010-04-01
#5 2010 5 2010-05-01
#6 2010 6 2010-06-01