T K
T K

Reputation: 415

Adding days to date columns using IF statements in R

Here is my data


data <- data.frame (med = c("A","A","B", "B", "C"),
        startdate = c("2014-01-21","2015-04-01","2016-03-15","2013-01-13","2014-01-02"),
        enddate = c("2014-11-21","2016-04-01","2017-04-15","2013-12-13","2015-09-13"))

I am trying to do a if statement to add number of days to the end date. For instance, if med = A then add 14 days to the end date. If med = B then add 21 days to the end date.

The following code I have tried


data$enddate[data$med=="A"] <- data$enddate + 14

But I keep getting the following error:Warning in NextMethod(.Generic) : number of items to replace is not a multiple of replacement length

Any help is appreciated!

Upvotes: 1

Views: 139

Answers (1)

jay.sf
jay.sf

Reputation: 72673

Using a named add vector.

add <- c(A=14, B=21, C=0)
transform(data, enddate=enddate + add[med])
#   med  startdate    enddate
# 1   A 2014-01-21 2014-11-21
# 2   A 2015-04-01 2016-04-01
# 3   B 2016-03-15 2017-04-15
# 4   B 2013-01-13 2013-12-13
# 5   C 2014-01-02 2015-09-13

First however, you may want to transform your dates to "Date" class.

dt <- grep('date', names(data))
data[dt] <- lapply(data[dt], as.Date)

Data:

data <- structure(list(med = c("A", "A", "B", "B", "C"), startdate = c("2014-01-21", 
"2015-04-01", "2016-03-15", "2013-01-13", "2014-01-02"), enddate = c("2014-11-21", 
"2016-04-01", "2017-04-15", "2013-12-13", "2015-09-13")), class = "data.frame", row.names = c(NA, 
-5L))

Upvotes: 1

Related Questions