[R] adding a date column with dplyr

Alice Domalik 9add2 at queensu.ca
Fri Aug 5 18:51:54 CEST 2016


Hi all,


I'm having some difficulties adding a conditional element to my code.

I have a time series data set that contains GPS tracking coordinates for a population of animals.


ID                Date                                   Latitude           Longitude
15K12         2014-05-22 04:33:00     50.67675        -129.6553

15K12         2014-05-22 04:35:00     50.45613        -129.4566
15K19         2014-05-24 06:44:00     50.34611        -129.5678    (and so on)

I added a new column to this dataset, called "Night", which is the day of tracking for each animal, but with the time of 21:30.


ID                Date                                  Latitude           Longitude       Night
15K12         2014-05-22 04:33:00     50.67675        -129.6553       2014-05-22 21:30:00

15K12         2014-05-22 04:35:00     50.45613        -129.4566       2014-05-22 21:30:00
15K19         2014-05-24 06:44:00     50.34611        -129.5678       2015-05-24 21:30:00

I used the following code to do this:
library(dplyr)
library(lubridate)
Sys.setenv(TZ="Canada/Pacific")
df<-df%>%
  group_by(ID) %>%
  mutate(Night=as.POSIXct(date(min(Date)) + days(0) + hours(21) + minutes(30), tz="Canada/Pacific"))

However, I need to add a conditional element, because for one animal, "Night" needs to be 1 day later. I tried this code...

df<-df%>%
  group_by(ID) %>%
  mutate(Night=ifelse(test=(id=='M16c'),yes=as.POSIXct(date(min(Date)) + days(1) + hours(21) + minutes(30), tz="Canada/Pacific"), no=as.POSIXct(date(min(Date)) + days(0) + hours(21) + minutes(30), tz="Canada/Pacific")))

The code runs, but instead of having a date, I get a string of numbers like "1403497200" in the column "Night".
Any ideas what the problem could be?

Thanks, Alice




	[[alternative HTML version deleted]]



More information about the R-help mailing list