R - Check If String Contains Dates Within Specific Date Range

R - check if string contains dates within specific date range

You can use convenient function between from either dplyr/data.table after converting to 'Date' class. The 'dateString' is a single string, which we can split at the white space using strsplit or just by using scan.

library(lubridate)
library(data.table)
between(mdy(scan(text=dateString, what='', quiet=TRUE)),
mdy(startDate), mdy(endDate))

The above single line can be split into different steps for easier understanding.

#split the string to substring at whitespace.
v1 <- scan(text=dateString, what='', quiet=TRUE)
#convert to Date class
v2 <- mdy(v1)
#use between to get a logical index of the dates
#that are between 'startDate' and 'endDate'
res <- between(v2, mdy(startDate), mdy(endDate))
res
#[1] TRUE FALSE TRUE FALSE

Just for completeness, if we need 'Yes/No' values in place of 'TRUE/FALSE' we can use ifelse. The ifelse part would be easier to understand. If elements are 'TRUE', it gets replaced with 'Yes' or else it will be replaced by 'No'.

 ifelse(res, 'Yes', 'No')
#[1] "Yes" "No" "Yes" "No"

Or numeric indexing to replace the values in 'res'.

 c('No', 'Yes')[res+1L]
#[1] "Yes" "No" "Yes" "No"

The above step may be a little confusing. But, whenever I find something less obvious, I split the code into the smallest possible code. Here, I would look for

 res+1L
#[1] 2 1 2 1

adding/multiplying a logical index coerces the logical index to binary integers i.e. 0/1. Here we added 1L or integer 1. What happens is that the TRUE values coerced to 1 will be added with the 1L to get 2 and FALSE coerced to 0 will be added with 1 and 0+1 = 1.

As the logical index is converted to numeric index, we use this to replace a vector of strings c('No', 'Yes'). Note that in the first position of the string is 'No' and in the second position it is 'Yes'. Based on the length of the numeric index i.e. '4' and the position index specified by that index, we replace the index with 'Yes/No'.


We could also this without using any external package as well.

 v2 <- as.Date(v1, '%m/%d/%Y')
v2 >= as.Date(startDate, '%m/%d/%Y') & v2 <= as.Date(endDate, '%m/%d/%Y')
#[1] TRUE FALSE TRUE FALSE

If we don't need to consider the 'startDate' and 'endDate', replace >=/<= with >/<

check if list of dates is within a date range in r

# put target years in a table
mastDF = data_frame(year = as.integer(mast.yr))

# count based on conditions
dat %>%
mutate(in_mast = count_matches(., mastDF, year >= byear, year <= dyear) > 0) %>%
as.tbl

# A tibble: 100 x 4
squirrel_id byear dyear in_mast
<int> <int> <int> <lgl>
1 6715 2006 2006 FALSE
2 22274 2016 2017 FALSE
3 20445 2014 2017 TRUE
4 19528 2013 2013 FALSE
5 2674 1995 1995 FALSE
6 1419 1992 1992 FALSE
7 15014 2004 2004 FALSE
8 10946 2009 2012 TRUE
9 4369 1998 1999 TRUE
10 4344 1992 1999 TRUE
# ... with 90 more rows

where count_matches is a helper function:

library(data.table)
count_matches = function(DF, targetDF, ...){
onexpr = substitute(list(...))
data.table(targetDF)[data.table(DF), on=eval(onexpr), allow.cart=TRUE, .N, by=.EACHI]$N
}

If you want both the count and whether the count is non-zero, this can be done by breaking it into a sequence of mutate arguments:

dat %>% 
mutate(
n_mast = count_matches(., mastDF, year >= byear, year <= dyear),
in_mast = n_mast > 0
) %>% as.tbl

# A tibble: 6 x 5
squirrel_id byear dyear n_mast in_mast
<int> <int> <int> <int> <lgl>
1 6715 2006 2006 0 FALSE
2 22274 2016 2017 0 FALSE
3 20445 2014 2017 1 TRUE
4 19528 2013 2013 0 FALSE
5 2674 1995 1995 0 FALSE
6 1419 1992 1993 1 TRUE

Spotfire TERR script to check if date string is within date range

I adjusted your code a bit. Spotfire sets the input as a vector. Adjust inputs and outputs as you want them to be. I used strsplit because I assume the data looks like this.Sample Image

also there is no need for assignments inside your ifelse statement. You just assign the outcome to your variable. I tested this code in Spotfire 6.5 and I get the correct results back.

startDate <- "01/01/2015"
endDate <- "07/01/2015"

MyCustomFunction <- function(startDate, endDate, dateString) {
outcome <- NULL
for (i in 1:length(dateString)) {
v1 <- strsplit(dateString[i], " ", fixed = TRUE)
v2 <- as.Date(unlist(v1), '%m/%d/%Y')
temp <- v2 >= as.Date(startDate, '%m/%d/%Y') & v2 <= as.Date(endDate,'%m/%d/%Y')
outcome <- c(test, ifelse(length(unique(temp))==1, ifelse(unique(temp)==TRUE, as.character(TRUE), as.character(FALSE)), as.character(FALSE)))
}
return(outcome)
}

output <- MyCustomFunction(startDate, endDate, dateString)

How do I determine if a given string has a date or time in it?

I would use 'grepl', but there will be a problem if there's a string with something in it that looks like a date, but isn't. Try the example below:

strings <- c("dfdsf 2014/01/02 dsfdsf", "fgfffdbf 2014-01-02 dfsdfdfd", "dfdfds 02/01/2014", "02/2014/01 dffsdfsd", "2014/01/02 00:30 sdgfsdgsdgvbds",  "02/2014/01 12:20:22 xcbfdgfdg", "01:11:22 02/2014/01 sdgsdgs", "00:30 2014-01-02 fdgfdgd", "NoDateHere")

findDates <- function(strings) {
pattern1 <- '[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]'
pattern2 <- '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]'
pattern3 <- '[0-9][0-9]/[0-9][0-9][0-9][0-9]/[0-9][0-9]'
pattern4 <- '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'

tdBool <- grepl(pattern1, strings) | grepl(pattern2, strings) | grepl(pattern3, strings) | grepl(pattern4, strings)
return(tdBool)
}

findDates(strings)

Check if the current date string is within or outside the range of two other dates

Instead of the date format "MMMM d" (e.g. "September 15"), you can convert the dates
to a string with the date format "MMdd" (e.g. "0915"). Then you can do a simple
string comparison between the current date, the start date and the expiry date.

For example,

"0915" < "1019" < "1220"

so October 19 is in the range from September 15 to December 20.

Checking between date ranges javascript

You can simply check if a date is in range with getTime()

JSBin

const isDateInRage = (startDate, endDate) => (dateToCheck) => {  return dateToCheck >= startDate && dateToCheck <= endDate}
const isInRangeOne = isDateInRage('2016-01-01', '2016-04-30')
console.log('inRange', isInRangeOne('2016-01-02'))console.log('outtOfRange', isInRangeOne('2016-07-02'))

Is there a way to check if a column is a Date in R?

You could try to coerce all the columns to as.Date and see which ones succeed. You would need to specify the format you expect dates to be in though. E.g.:

data <- data.frame(
Date=c("10/11/2012","10/12/2012"),
AE=c(1211,100),
Percent=c(0.03,0.43)
)

sapply(data, function(x) !all(is.na(as.Date(as.character(x),format="%d/%m/%Y"))))
#Date AE Percent
#TRUE FALSE FALSE

Check if date falls between 2 dates

Swift 2

For a better answer see Swift ≧ 3.

You already have the code for conversion of your date string in KeysData to NSDate. Assuming you have the two dates in startdate and enddate, all you have to do is check if the current date is in between:

let startDate = ...
let endDate = ...

NSDate().isBetween(date: startDate, andDate: endDate)

extension NSDate {
func isBetweeen(date date1: NSDate, andDate date2: NSDate) -> Bool {
return date1.compare(self) == self.compare(date2)
}
}

Edit: If you want to perform an inclusive range check, use this condition:

 extension NSDate {
func isBetween(date date1: NSDate, andDate date2: NSDate) -> Bool {
return date1.compare(self).rawValue * self.compare(date2).rawValue >= 0
}
}


Related Topics



Leave a reply



Submit