tca*_*h21 3 r date apply dataframe
这似乎应该更容易,我相信有人可以帮助我.我正在尝试使用lubridate包中的floor_date()将日期的data.frame更改为每个日期到其各自月份的第一个日期,但是其中一些日期是NA.我宁愿不用NA代替虚拟日期.
我试过以下:
library(lubridate)
a<-c(as.Date("2011-05-04"), as.Date("2011-06-12"))
b<-c(as.Date("2012-03-01"), NA)
test <- data.frame(a,b)
apply(test, 1, function(y) sapply(y, function(x) if(!is.na(x)) floor_date(x, "month") else na.pass(x)))
apply(test, 1, function(y) ifelse(!is.na(y)), floor_date(y, "month"), na.pass(y))
Run Code Online (Sandbox Code Playgroud)
第一个调用返回:
Error in object[[name, exact = TRUE]] : subscript out of bounds
Run Code Online (Sandbox Code Playgroud)
第二个调用返回:
Error in update.default(x, mdays = 1, hours = 0, minutes = 0, seconds = 0) :
need an object with call component
Run Code Online (Sandbox Code Playgroud)
感谢您的任何帮助!
我不知道有什么关于lubridate,但你可以通过基地R提供的出色的日期处理设施轻松完成.
这是一个小辅助函数,可以执行您想要的计算而无需投诉:
firstOfMonth <- function(dates) {
as.Date(strftime(dates, format="%Y-%m-01"))
}
firstOfMonth(a)
# [1] "2011-05-01" "2011-06-01"
firstOfMonth(b)
# [1] "2012-03-01" NA
data.frame(lapply(test, firstOfMonth))
# a b
# 1 2011-05-01 2012-03-01
# 2 2011-06-01 <NA>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6777 次 |
最近记录: |