gpt4 book ai didi

r - 使用 R 比较日期

转载 作者:行者123 更新时间:2023-12-04 11:21:27 26 4
gpt4 key购买 nike

我有两个 csv 文件。

一个文件列出了员工离职的时间和原因。

EmployeeID,Department,Separation_Type,Separation_Date,FYFQ    
119549,Sales,Retirement,09/30/2013
2629053,Sales,Termination,09/30/2013
120395,Sales,Retirement,11/01/2013
122450,Sales,Transfer,11/30/2013
123962,Sales,Transfer,11/30/2013
1041054,Sales,Resignation,12/01/2013
990962,Sales,Retirement,12/14/2013
135396,Sales,Retirement,01/11/2014

另一个文件是一个查找表,显示每个财政季度的开始和结束日期:

FYFQ,Start,End  
FY2014FQ1,10/1/2013,12/31/2013
FY2014FQ2,1/1/2014,3/31/2014
FY2014FQ3,4/1/2014,6/30/2014
FY2014FQ4,7/1/2014,9/30/2014
FY2015FQ1,10/1/2014,12/31/2014
FY2015FQ2,1/1/2015,3/31/2015

我希望 R 找到 Separation_Date 发生的 FYFQ,并将其打印到数据的第四列。

输入:

Separations.csv:   
>EmployeeID,Department,Separation_Type,Separation_Date,FYFQ
>990962,Sales,Retirement,12/14/2013
>135396,Sales,Retirement,01/11/2014

财政季度日期.csv:

>FYFQ,Start,End  
>FY2013FQ4,7/1/2013,9/30/2013
>FY2014FQ1,10/1/2013,12/31/2013
>FY2014FQ2,1/1/2014,3/31/2014

期望的输出:
输出.csv:

>EmployeeID,Department,Separation_Type,Separation_Date,FYFQ      
>990962,Sales,Retirement,12/14/2013,FY2014FQ1
>135396,Sales,Retirement,01/11/2014,FY2014FQ2

我假设有一些函数会遍历 FiscalQuarterDates.csv 并评估每个离职日期是否在 FYFQ 中,但我不确定。

对实现此目的的最佳方式有何想法?

这是有效的。

#read in csv and declare th3 4th column a date
separations <- read.csv(file="Separations_DummyData.csv", head=TRUE,sep=",",colClasses=c(NA,NA,NA,"Date"))


#Use the zoo package (I installed it) to convert separation_date to quarter type and then set the quarter back by 1/4. Then construct the variable with FYyFQq.
library(zoo)
separations$FYFQ <- format(as.yearqtr(separations$Separation_Date, "%m/%d/%Y") + 1/4, "FY%YFQ%q")

#Write out this to CSV in working directory.
write.csv(separations, file = "sepscomplete.csv", row.names = FALSE)

最佳答案

你真的不需要第二个数据框:一个简单的函数就可以解决这个问题:

yr<-with(firstdf,as.numeric(substr(Seperation_Date,7,10)))
mth<-with(firstdf,as.numeric(substr(Seperation_Date,1,2)))


firstdf$FYFQ<-with(firstdf,
ifelse(mth<=3,paste0("FY",yr,"FQ2"),
ifelse(mth>3 & mth<=6,paste0("FY",yr,"FQ3"),
ifelse(mth>7 & mth<=9,paste0("FY",yr,"FQ4"),
paste0("FY",yr+1,"FQ1")
))))

关于r - 使用 R 比较日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30226920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com