gpt4 book ai didi

r - 日期上的嵌套 If 语句

转载 作者:行者123 更新时间:2023-12-04 12:16:45 24 4
gpt4 key购买 nike

我有一个数据框 df如下。

Id     ProcessDate
10 2011-12-29 14:14:00
11 2011-12-29 14:16:00
12 2011-12-29 14:14:00
13 2011-12-29 14:20:00
14 2011-12-29 14:49:00
15 2011-12-29 14:51:00
16 2011-12-29 14:53:00
17 2011-12-29 15:11:00
18 2011-12-29 15:13:00
19 2011-12-29 15:10:00
20 2011-12-29 15:21:00
21 2011-12-29 14:34:00
22 2011-12-29 15:26:00

我正在尝试创建第三列 Status将包含这三个值之一 {Before, during , after }基于这个条件。
 if  (df$ProcessDate < 2011-12-29 14:48:00)
then df$Status = "Before"
else if (df$ProcessDate > 2011-12-29 14:48:00 & df$ProcessDate < 2011-12-29 15:16:00)
then df$Status = "Between"
else df$Status = "After"

最终的数据框应如下所示。
Id     ProcessDate              Status
10 2011-12-29 14:14:00 Before
11 2011-12-29 14:16:00 Before
12 2011-12-29 14:14:00 Before
13 2011-12-29 14:20:00 Before
14 2011-12-29 14:49:00 Between
15 2011-12-29 14:51:00 Between
16 2011-12-29 14:53:00 Between
17 2011-12-29 15:11:00 Between
18 2011-12-29 15:13:00 Between
19 2011-12-29 15:10:00 Between
20 2011-12-29 15:21:00 After
21 2011-12-29 14:34:00 After
22 2011-12-29 15:26:00 After

我尝试了几件事,但没有奏效,非常感谢有关此问题的任何帮助。

最佳答案

这可能是一种可能的解决方案

ids = c(10, 11, 12, 13, 14, 15, 16, 17, 18,  19, 20, 21, 22)      
date = c('2011-12-29 14:14:00', '2011-12-29 14:16:00', '2011-12-29 14:14:00', '2011-12-29 14:20:00', '2011-12-29 14:49:00', '2011-12-29 14:51:00', '2011-12-29 14:53:00', '2011-12-29 15:11:00', '2011-12-29 15:13:00', '2011-12-29 15:10:00', '2011-12-29 15:21:00', '2011-12-29 14:34:00', '2011-12-29 15:26:00')
df <- data.frame(Id = ids,
ProcessDate = strptime(date, format = '%Y-%m-%d %H:%M:%S'))


date.status.before <- strptime('2011-12-29 14:48:00', format = '%Y-%m-%d %H:%M:%S')
date.status.after <- strptime('2011-12-29 15:16:00', format = '%Y-%m-%d %H:%M:%S')
ProcessDateStatus <- function(process.date) {
if (process.date < date.status.before)
"Before"
else if (process.date > date.status.before & process.date < date.status.after)
"Between"
else
"After"
}
df$Status <- lapply(df$ProcessDate, ProcessDateStatus)

导致

   Id         ProcessDate  Status
1 10 2011-12-29 14:14:00 Before
2 11 2011-12-29 14:16:00 Before
3 12 2011-12-29 14:14:00 Before
4 13 2011-12-29 14:20:00 Before
5 14 2011-12-29 14:49:00 Between
6 15 2011-12-29 14:51:00 Between
7 16 2011-12-29 14:53:00 Between
8 17 2011-12-29 15:11:00 Between
9 18 2011-12-29 15:13:00 Between
10 19 2011-12-29 15:10:00 Between
11 20 2011-12-29 15:21:00 After
12 21 2011-12-29 14:34:00 Before
13 22 2011-12-29 15:26:00 After

关于r - 日期上的嵌套 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39652739/

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