oercim
oercim

Reputation: 1848

if statement with dates in R

I have a date formatted data frame(df). A sample of it is like:

df<- as.data.frame(as.factor(c("16.04.2015", "04.08.2014", "11.09.2013",  "20.11.2015", "04.04.2014")))
colnames(df)<-"date"

Namely;

date
16.04.2015
04.08.2014
11.09.2013
20.11.2015
04.04.2014

I want to assign "1" between two specific dates. Let say I want to assign "1" dates for between 10.02.2014 and 15.08.2014.Let "value" column be defined as the assign values. So the desired output is:

date        value
16.04.2015  0
04.08.2014  1
11.09.2013  0
20.11.2015  0
04.04.2014  1

How can I do that with if statements in R? Or is there any other way? I will be very glad for any help. Thanks a lot.

Upvotes: 1

Views: 5574

Answers (2)

rawr
rawr

Reputation: 20811

contrary to popular belief, it is definitely not necessary to use data table

df <- data.frame(date = as.Date(c("16.04.2015", "04.08.2014", "11.09.2013",
                                  "20.11.2015", "04.04.2014"), '%d.%m.%Y'))



`%between%` <- function(x, interval) x >= interval[1] & x <= interval[2]

df <- within(df, value <- 1 * (date %between% as.Date(c('2014-02-10', '2014-08-15'))))

#         date value
# 1 2015-04-16     0
# 2 2014-08-04     1
# 3 2013-09-11     0
# 4 2015-11-20     0
# 5 2014-04-04     1

Upvotes: 4

akrun
akrun

Reputation: 887108

You could use between from data.table

library(data.table)
setDT(df)[, value:=(as.Date(date, '%d.%m.%Y') %between% 
                       c('2014-02-10', '2014-08-15'))+0L][]
#         date value
#1: 16.04.2015     0
#2: 04.08.2014     1
#3: 11.09.2013     0
#4: 20.11.2015     0
#5: 04.04.2014     1

Upvotes: 4

Related Questions