Menu
  • HOME
  • TAGS

How to create date from datetime (using lubridate)?

r,posixct,lubridate

You can just use round_date round_date(a, "day") [1] "2014-01-02 UTC" EDIT You do need to be careful with rounding the time though. For complete equivalence here you would need to use floor_date. identical(ymd("2014-01-01"), floor_date(a, "day")) [1] TRUE ...

How to select date range with POSIXct type

r,lubridate

If DATE contains only dates (without hours and etc, like in your example data above) you can convert it into as.Date class and then operate on it model.weather$DATE <- as.Date(model.weather$DATE) model.weather <- subset(model.weather, DATE >= "2006-04-01" & DATE <= "2011-03-01") or (a better solution) model.weather <- model.weather[model.weather$DATE >= "2006-04-01" &...

How to flatten/merge overlapping time periods in R

r,date,lubridate

Here's a possible solution. The basic idea here is to compare lagged start date with the maximum end date "until now" using the cummax function and create an index that will separate the data into groups data %>% group_by(ID) %>% mutate(indx = c(0, cumsum(as.numeric(lead(start)) > cummax(as.numeric(end)))[-n()])) %>% group_by(ID, indx) %>%...

Error with durations created from a data.table using lubridate & dplyr

r,data.table,dplyr,lubridate

You can try by converting the interval output to either character class (as the interval output is not a vector) or wrap with as.duration (from @Jake Fisher) durations <- lakers.dt %>% mutate(better.date = ymd(date)) %>% group_by(player) %>% summarize(min.date = min(better.date), max.date = max(better.date)) %>% mutate(duration= as.duration(interval(min.date, max.date)) ) Or use...

Exclusive time intervals in R's lubridate

r,posixct,lubridate

Sure thing. I searched lubridate on github to find where %within% is defined. A couple tweaks to the code (changing <= to <): "%my_within%" <- function(a,b) standardGeneric("%my_within%") setGeneric("%my_within%") setMethod("%my_within%", signature(b = "Interval"), function(a,b){ if(!is.instant(a)) stop("Argument 1 is not a recognized date-time") a <- as.POSIXct(a) (as.numeric(a) - as.numeric([email protected]) < [email protected]) &...

How to convert unix timestamp (milliseconds) and timezone in R?

r,datetime,unix-timestamp,lubridate,timestamp-with-timezone

It looks like the timezone column is the timezone offset, in milliseconds. I assume that means the timezone column will adjust for daylight saving time manually So you should add the time and timezone columns before converting to POSIXct. You should also set the tz to "UTC" so no DST...

Apply a character variable of time zones to individual date time values parsed in lubridate

r,datetime,timezone,lubridate

Could try: library(lubridate) ## list seems better at preserving POSIXct class trial <- list() for (i in 1:nrow(df)) trial[[i]] <- ymd_hms(df$dpt[i], tz = df$dtz[i], locale = "en_US") ...

Looping through date in R loses format

r,loops,date,lubridate

Try this for (yr in as.list(yearrange)) { show(yr) } I think for (yr in yearrange) coerces yearrange into a vector and POSIXct is not one of the supported types that vector coerces into....

Adding lubridate dates to vector changes timezone and thus date

r,date,lubridate

That's because lubridate::mdy assumes UTC. When you wrap it around c(), it reverts back to your local timezone EDT because c() does not pass on the timezone attribute: > attr(mdy("5/4/2015", tz = "EDT"), "tzone") # [1] "EDT" > attr(c(mdy("5/4/2015", tz = "EDT")), "tzone") # NULL You can do: Sys.setenv(TZ =...

Tidyr's gather() with NAs

r,lubridate,tidyr

The data is not being converted to strings, it is dropping back to the integer representation of the seconds since 1970-01-01, which is what the original Date values in df represent: x <- df$bday_01 x #[1] "2015-03-09 UTC" "2015-03-09 UTC" attributes(x) <- NULL x #[1] 1425859200 1425859200 The warning message...

Why always get month=0 in as.period (lubridate package) in R

r,lubridate

Create an interval, then coerce it to a period: library(lubridate) ii <- new_interval(dmy("01/05/1981"),dmy("30/07/1979")) as.period(ii,units="months") [1] "-21m -1d 0H 0M 0S" res <- as.period(ii,units="years") [1] "-1y -9m -1d 0H 0M 0S" EDIT I don't think that you can remove the hour,minutes parts. But you can write your print function: paste0(c([email protected],[email protected],[email protected]),c('y','m','d'),collapse=' ')...

R aggregate a dataframe by hours from a date with time field

r,dplyr,lubridate

library(readr) library(dplyr) library(lubridate) df <- read_delim('DateTime|Value 3/14/2015 12:00:00|23 3/14/2015 13:00:00|24 3/15/2015 12:00:00|22 3/15/2015 13:00:00|40',"|") df %>% mutate(hour_of_day = hour(as.POSIXct(strptime(DateTime, "%m/%d/%Y %H:%M:%S")))) %>% group_by(hour_of_day) %>% summarise(meanValue = mean(Value)) breakdown: Convert column of DateTime (character) into formatted time then use hour() from lubridate to pull out just that hour value and put...

Outputting various subsets from one data frame based on dates

r,loops,subset,lubridate

I might do as following. Only end dates seem to be necessary as start dates are just 1 year before. Loop is made using lapply() which iterates over all end dates. Subsetting is done mainly with difftime() by filtering any non-zero time difference between the two dates. set.seed(24) df1 <-...

mapping months to axis built with yeardays?

r,ggplot2,lubridate

How about adding scale_x_continuous? There is probably a better way to do this, but the following works: scale_x_continuous(breaks = cumsum(c(1, 31, 30, 28, 30, 31, 30, 31, 31, 30, 31, 30)), label = c('Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec')) ...

Combining dplyr::mutate with lubridate::ymd_hms in R randomly causes segfault

r,segmentation-fault,dplyr,lubridate

90% sure this is a bug in latest version of dplyr (0.4.2), see this issue here: https://github.com/hadley/dplyr/issues/1231 Downgrading my version of dplyr to 0.4.1 as follows fixes the issue: packageurl = "http://cran.r-project.org/src/contrib/Archive/dplyr/dplyr_0.4.1.tar.gz" install.packages(packageurl, repos=NULL, type="source", dependencies = TRUE) ...

How do I transform a complicated character string (Mon Apr 06 22:19:45 PDT 2009) into a date/time in r?

r,date,time,character,lubridate

I don't think you can convert a date-time string with an embedded time zone specifier x2 <- "Mon Apr 06 22:19:45 2009" strptime(x2,"%a %b %d %H:%M:%S %Y") ## [1] "2009-04-06 22:19:45 EDT" You could use regular expressions to extract the time zone and use it as the tz argument: strptime(x2,"%a...

R convert number into time

r,data.frame,posixct,lubridate

If TIMEIN is always six characters (i.e., there's a leading zero for times before 10 AM), then you can do this: df$TIMEIN = paste0(substr(df$TIMEIN,1,2),":",substr(df$TIMEIN,3,4),":", substr(df$TIMEIN,5,6)) df$TIMEIN = hms(df$TIMEIN) ...

Display time in hrs and minutes format using lubridate package in R : Dataframe Issue

r,time,lubridate

hm transforms a character or numeric vector into a Period object. i.e.: str(hm("10:30")) ## Formal class 'Period' [package "lubridate"] with 6 slots ## [email protected] .Data : num 0 ## [email protected] year : num 0 ## [email protected] month : num 0 ## [email protected] day : num 0 ## [email protected] hour :...

Apply + lubridate returns numeric

r,apply,lubridate

We don't need apply with MARGIN=1. Instead, we can paste the columns by with(birds, paste(year, month, day, sep="-")) and wrap it with as.Date to convert to 'Date' class. The output of ymd is POSIXct class, within the apply, it will be coerced to 'numeric' form. library(lubridate) library(dplyr) mutate(birds, date=ymd(paste(year, month,...

Creating a year/week format for current date in R

r,lubridate

You might want to adjust lubridate::isoweek to return the desired string: isodate <- function (x = Sys.Date()) { xday <- ISOdate(year(x), month(x), day(x), tz = tz(x)) dn <- 1 + (wday(x) + 5)%%7 nth <- xday + ddays(4 - dn) jan1 <- ISOdate(year(nth), 1, 1, tz = tz(x)) return(sprintf("%s/%02d", format(nth,...

ymd with vector of dates

r,lubridate

Your issue is that your vector is not just year, month, day (ymd), but also hour, minute, second (hms). Consider using this instead: ymd_hms(d) If you want to just extract the date, you can use: strftime(ymd_hms(d),'%Y-%m-%d') ...

R and lubridate: do the intervals in x fit into any of the intervals in y?

r,intervals,lubridate

I would approach this using data.tables foverlaps function First, we will convert to data.table objects, create start and end intervals, and sort campus.df by these intervals library(data.table) setDT(task.df)[, `:=`(start = as.POSIXct(paste(Start.Date, Start.Time)), end = as.POSIXct(paste(End.Date, End.Time)))] setkey(setDT(campus.df)[, `:=`(start = as.POSIXct(paste(Start.Date, Start.Time)), end = as.POSIXct(paste(End.Date, End.Time)))], start, end) Then, we could...

Plotting pre-computed statistics on POSIX dates with ggplot's geom_boxplot

r,ggplot2,data.table,lubridate

It looks like the code for geom_boxplot does division to try to calculate box widths. As far as I can tell that branch seem unavoidable. A hack-y workaround would be to actually define division for date time values. `/.POSIXt`<-function(e1,e2) as.numeric(e1)/as.numeric(e2) Running this before your code seems to produce the requested...

Convert separate 'year' and 'day' columns into one 'date' column with lubridate?

r,lubridate

You could use base dates rather than lubridate if you like If this is your sample data dd<-data.frame( year = rep(2008,4), day = 1:4 ) Then you can run years <- unique(dd$year) yearstarts <- setNames(as.Date(paste0(years, "-01-01")), years) newdates <- yearstarts[as.character(dd$year)] + dd$day - 1 Which produces cbind(dd, newdates) # year...

Summing rows by month in R

r,data.table,aggregate,dplyr,lubridate

I create the data set by data <- read.table( text=" Date Hour Melbourne Southern Flagstaff 1 2009-05-01 0 0 5 17 2 2009-05-01 2 0 2 1 3 2009-05-01 1 0 11 0 4 2009-05-01 3 0 3 8 5 2009-05-01 4 0 1 0 6 2009-05-01 5 0 49...

R - week function returns unexpected values

r,calendar,week-number,lubridate

Have a look at ?week Weeks is the number of complete seven day periods that have occured between the date and January 1st, plus one. isoweek returns the week as it would appear in the ISO 8601 system, which uses a reoccuring leap week. Using the function isoweek you get...