I have the following problem. I have two vectors on with characters (c.vec), one with dates(d.vec). I want to calculate a certain time interval if the char vector has a certain attribute. As the if-statement should check each row, I read that I need to use nested ifelse statements (as for certain months in the date vector, a specific date should be used to calculate the time interval). My ifelse statement should calculate as follows:
1) If the c.vec == 'Tree' and the month of d.vec is after October – then calculate 15.07.YearAfterd.vec - date of d.vec and overwrite another vector called d.diff (this vector already has numeric values stored in it) with the outcome
2) If the c.vec == 'Tree' and the month of d.vec is after May– then calculate 15.03.YearAfterd.vec - date of d.vec and overwrite d.diff with the outcome
3) If the c.vec == 'Tree' and the month of d.vec before May – then calculate 15.07.YearOfd.vec- date of d.vec and overwrite d.diff with the outcome
4) If c.vec =! 'Tree' then just use the value already stored in d.diff and do not overwrite anything
Here is what I tried (however, it just returns NAs and does not even overwrite the d.diff entries at all. I just prints the NAs in the console) - with an example:
c.vec <- c('tree','tree','tree','flower','flower')
d.diff <- c(150,80,97,52,74)
d.vec <- as.Date(c('2016-11-24','2017-06-14','2016-02-21','2017-05-07','2016-04-18'))
ifelse(c.vec=='tree',
# Check if date is after October. The as.Date() part should return 15.07. of the year after d.vec
ifelse(month(d.vec)>10,d.diff <- as.numeric(as.Date(capture.output(cat(year(d.vec)+1,'-07-15')),'%Y -%m-%d')-d.vec),
# Check if date is after May
ifelse(month(d.vec)>5,d.diff <- as.numeric(as.Date(capture.output(cat(year(d.vec)+1,'-02-15')),'%Y -%m-%d')-d.vec),
# Else, use 15.07. of the year of d.vec to calculate the time difference
d.diff <- as.Date(capture.output(cat(year(d.vec),'-07-15')),'%Y -%m-%d')-d.vec)),
# if c.vec =! tree just use the existing values in d.diff
d.diff <- d.diff)
How do I need to adjust it that I get the specific time differences in the d.diff vector? I also tried to use store the vectors in a data frame and then use df.name$... to use the entries of the vectors but it just returns NAs as well. Thanks for the help!
Aucun commentaire:
Enregistrer un commentaire