使用dplyr进行条件变异

时间:2016-08-05 04:16:03

标签: r dplyr

首先,我在堆栈溢出时发现了另外两个类似的问题,但我仍然无法弄清楚如何解决这个特定的问题......

最初,我想在我的数据框中创建一个新列,其中包含每只鸟被跟踪的日期,但时间是21:30。

例如,我想从此开始...

BirdID    latitude      longitude   Date
15K12     492719.9      5634805     2015-06-23 18:25:00
15K12     492491.5      5635018     2015-06-23 18:27:00
15K70     455979.1      5653581     2015-06-24 19:54:00  
15K70     456040.9      5653668     2015-06-24 19:59:00

对此......

BirdID   latitude    longitude   Date                    Night
15K12   492719.9     5634805     2015-06-23 04:25:00     2015-06-23 21:30:00
15K12   492491.5     5635018     2015-06-23 04:27:00     2015-06-23 21:30:00
15K70   455979.1     6535815     2015-06-24 03:54:00     2015-06-24 21:30:00 
15K70   456040.9     5653668     2015-06-24 03:59:00     2015-06-24 21:30:00

为此,我使用了这段代码......

df <- df %>%
  group_by(BirdID) %>%
  mutate(night=as.POSIXct(date(min(Date)) + days(0) + hours(21) +
  minutes(30),tz="Canada/Pacific"))

然而,现在我想对某些人使用稍微不同的时间。 例如,对于BirdID = 15K12,15K70,15K30,我希望时间是21:30 但对于BirdID = 14K22,14K50,14K62,我希望时间是21:20

如何将此条件合并到我的代码中?

1 个答案:

答案 0 :(得分:0)

以下是使用str_sub软件包中的stringrpaste的解决方案:

df = data.frame(BirdID = sample(LETTERS[1:6],20, replace = T), 
Date = latemail(20, st = "2015/06/20", et = "2015/06/25"))
# for latemail function see 
http://stackoverflow.com/questions/14720983/efficiently-generate-a-random-sample-of-times-and-dates-between-two-dates 

library(stringr)
group_1 = c("A", "D", "E") # 15K70 in your example
group_2 = c("B", "C", "F") # 14K22 in your example

df$Night = as.POSIXct(paste(str_sub(df$Date,1,10), "21:30:00"))
df$Night[df$BirdID %in% group_2] = 
as.POSIXct(paste(str_sub(df$Date[df$BirdID %in% group_2],1,10), "21:20:00"))

df

   BirdID                Date               Night
1       F 2015-06-20 04:01:12 2015-06-20 21:20:00
2       F 2015-06-21 06:39:40 2015-06-21 21:20:00
3       B 2015-06-21 08:26:48 2015-06-21 21:20:00
4       E 2015-06-21 11:38:00 2015-06-21 21:30:00
5       A 2015-06-21 18:11:13 2015-06-21 21:30:00
6       C 2015-06-22 03:06:05 2015-06-22 21:20:00
7       A 2015-06-22 03:50:52 2015-06-22 21:30:00
8       C 2015-06-22 05:22:32 2015-06-22 21:20:00
9       F 2015-06-22 07:09:57 2015-06-22 21:20:00
10      C 2015-06-22 15:17:08 2015-06-22 21:20:00
11      E 2015-06-23 05:29:51 2015-06-23 21:30:00
12      C 2015-06-23 09:10:33 2015-06-23 21:20:00
13      D 2015-06-23 09:17:44 2015-06-23 21:30:00
14      F 2015-06-23 11:15:53 2015-06-23 21:20:00
15      F 2015-06-24 04:40:47 2015-06-24 21:20:00
16      D 2015-06-24 04:49:52 2015-06-24 21:30:00
17      F 2015-06-24 05:05:39 2015-06-24 21:20:00
18      F 2015-06-24 09:50:55 2015-06-24 21:20:00
19      F 2015-06-24 15:17:53 2015-06-24 21:20:00
20      C 2015-06-24 20:17:21 2015-06-24 21:20:00