如何设置长度为84的变量,为非闰年的前84天提供正确的月份(使用标签“jan”,“feb”,“march”)?
答案 0 :(得分:2)
您可以执行以下操作(更改year
的值以选择其他年份):
year <- 2001
days <- as.Date(paste(year, "/01/01", sep = "")) + seq.int(0, 83)
months(days, abbreviate = TRUE)
# [1] "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan"
#[13] "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan"
#[25] "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Jan" "Feb" "Feb" "Feb" "Feb" "Feb"
#[37] "Feb" "Feb" "Feb" "Feb" "Feb" "Feb" "Feb" "Feb" "Feb" "Feb" "Feb" "Feb"
#[49] "Feb" "Feb" "Feb" "Feb" "Feb" "Feb" "Feb" "Feb" "Feb" "Feb" "Feb" "Mar"
#[61] "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar"
#[73] "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar"
您可以按如下方式检查年份是否为闰年:
if (table(months(days))["February"] == 29)
cat(paste(year, "is a leap year.\n"))
答案 1 :(得分:2)
Altenative#1:
library(zoo)
days <- as.Date('2014-01-01') + seq.int(84)-1
get_month_given_date <- zoo(months(days, abbreviate = TRUE),order.by=days)
#Example
get_month_given_date[as.Date('2014-02-28')]
get_month_given_date[as.Date(c('2014-01-03','2014-03-04'))]
备选方案#2:
library(zoo)
strsplit(as.character(as.yearmon("2007-03-01"))," ")[[1]][1]
闰年检查:
is_leap_year <- function(year){if((year%%4==0 & year%%100!=0) | year%%400==0 ) return(TRUE) else return(FALSE)}
#Examples
is_leap_year(2000)
is_leap_year(1900)
is_leap_year(2012)
is_leap_year(2014)