R-周函数返回意外值 [英] R - week function returns unexpected values

查看:72
本文介绍了R-周函数返回意外值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在R的一年中找到星期,以获取日期列表.但是,输出结果很奇怪.

I am looking to find the week within a year in R for a list of dates. However, The outputs are rather weird.

参见下文:

week("2000-01-01")
week("2000-01-06")
week("2000-01-07")
week("2000-01-13")
week("2000-01-14")

这将返回1、1、2、2、3

This returns 1, 1, 2, 2, 3

但是,如果您查看日历:

However, if you look at a calendar: http://calendars.generalblue.com/content/images/calendars/2000/01-January-2000-Calendar.png

您希望它是1、2、2、3、3.

You'd expect it to be 1, 2, 2, 3, 3.

由于某种原因,此日期在周四结束.那不是很奇怪吗?

For some reason, this rolls over on a Thursday. Isn't that strange?

有人知道我应该怎么做才能获得预期的1,2,2,3,3结果吗?

Does anyone know how I should do this to get the expected 1, 2, 2, 3, 3 results?

推荐答案

看看?week

周数是已经发生的完整的7天时间段数 在日期和1月1日之间加上1. isoweek返回星期 就像在ISO 8601系统中出现的那样 周.

Weeks is the number of complete seven day periods that have occured between the date and January 1st, plus one. isoweek returns the week as it would appear in the ISO 8601 system, which uses a reoccuring leap week.

使用功能isoweek,您将获得以下结果.

Using the function isoweek you get the following result.

require(lubridate)
dates <- c("2000-01-01","2000-01-06","2000-01-07","2000-01-13","2000-01-14") 
sapply(dates, isoweek) 
2000-01-01 2000-01-06 2000-01-07 2000-01-13 2000-01-14 
        52          1          1          2          2

那么一周什么时候为您开始"呢?在以下日期函数中,一周从星期日开始

So when does a week "start" for you? In the following date-function a week start's on Sunday

require(lubridate)
my_week <- function(x){
  # fst monday of the same year
  first_sun <- as.POSIXct(paste0(year(x),"-01-Mon"), format = "%Y-%U-%a")
  (yday(x) + (7 - yday(first_sun) + 1)) %/% 7
}

dates <- seq(as.Date("2000-01-01"), as.Date("2000-01-15"), by=1)
a <- sapply(dates, my_week)
names(a) <- dates

> a
2000-01-01 2000-01-02 2000-01-03 2000-01-04 2000-01-05 
         0          1          1          1          1          
2000-01-06 2000-01-07 2000-01-08 2000-01-09 2000-01-10 
         1          1          1          2          2    
2000-01-11 2000-01-12 2000-01-13 2000-01-14 2000-01-15 
         2          2          2          2          2 

这篇关于R-周函数返回意外值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆