使用系统1从ms-excel中的WEEKNUM函数中提取R中的周数

问题描述 投票:0回答:2

我想使用与Excel中的WEEKNUM函数相同的系统1来提取R中的周数。

请参考下图

enter image description here

我已经探索了从R中的日期中提取周数的所有可用选项,但没有任何东西可以实现我的目标

library(parsedate)
dates =c("12/25/2015", "12/26/2015", "12/27/2015", "12/28/2015", "12/29/2015", "12/30/2015", "12/31/2015", "1/1/2016", "1/2/2016", "1/3/2016", "12/24/2016", "12/26/2016", "12/27/2016", "12/28/2016", "12/29/2016", "12/30/2016", "1/1/2017", "1/2/2017")
#Converting dates into date format in R 
dates = as.Date(parse_date(dates), format = "%Y-%m-%d")

desired_output

52 52 53 53 53 53 53 1 1 2 2 52 53 53 53 53 53 53 1 1

任何人都可以帮我找出一种方法来做到这一点。

注意: - 请在标记之前验证可能重复的内容。这可能最终会使那些能够为问题提供解决方案的人偏离。

r excel date week-number
2个回答
0
投票

哇似乎不仅仅是满足了眼睛。似乎1月1日是在星期天(例如2006-01-01,2012-01-01),在这些1月1日的日期里,q的"%U""01"而不是"00"。下面是一个黑客。

df <- data.frame(dates=as.Date(c(sapply(seq(as.Date("2000-01-01"), by="1 year", length.out=20), function(x) {
    x + -7:7  
})), origin="1970-01-01"))

df$rweeknum <- ifelse(format(as.Date(format(df$dates, "%Y-01-01")), "%a")=="Sun",
    as.integer(strftime(as.Date(df$dates, "%m/%d/%Y"), format = "%U")),
    as.integer(strftime(as.Date(df$dates, "%m/%d/%Y"), format = "%U")) + 1)

#open and check in Excel
write.csv(df, "dates.csv", row.names=FALSE)
shell("dates.csv")

在提出R Core问题之前,需要进一步调查并仔细检查。其他人也可以验证您是否获得了相同的行为? all(format(seq(as.Date("1970-01-01"), by="1 year", length.out=100), "%U")=="00")


0
投票

这为我提供了所需的输出。 (OP:如果边缘情况处理不当,请编辑问题以包含它们......)

建立:

dates =c("12/25/2015", "12/26/2015", "12/27/2015", 
        "12/28/2015", "12/29/2015", "12/30/2015", "12/31/2015", 
        "1/1/2016", "1/2/2016", "1/3/2016", "1/4/2016", "1/5/2016", 
        "1/6/2016")
dates = as.Date(dates,format="%m/%d/%Y")

兑换:

as.numeric(format(dates,"%U"))+1
## [1] 52 52 53 53 53 53 53  1  1  2  2  2  2

系统信息:

R version 3.4.3 (2017-11-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: OS X El Capitan 10.11.6

locale:
[1] en_CA.UTF-8/en_CA.UTF-8/en_CA.UTF-8/C/en_CA.UTF-8/en_CA.UTF-8
© www.soinside.com 2019 - 2024. All rights reserved.