mercredi 28 novembre 2018

r - Ordering problems when using mutate with ifelse conditional to date

I'm trying to use mutate to create a column that takes the value of one column up to a point and then uses cumprod to fill the rest of the observations based on the values of another column.

I tried combining mutate with ifelse but the order of the statements is not correct and I can't figure out why

Below I reproduce a more basic example that replicates my problem:

foo1 <- data.frame(date=seq(2005,2018,1))
foo1 %>% mutate(h=ifelse(date>2008, seq(1,11,1), 99))

The output is:

   date  h
1  2005 99
2  2006 99
3  2007 99
4  2008 99
5  2009  5
6  2010  6
7  2011  7
8  2012  8
9  2013  9
10 2014 10
11 2015  1
12 2016  2
13 2017  3
14 2018  4

And I'd like it to be:

   date  h
1  2005 99
2  2006 99
3  2007 99
4  2008 99
5  2009  1
6  2010  2
7  2011  3
8  2012  4
9  2013  5
10 2014  6
11 2015  7
12 2016  8
13 2017  9
14 2018 10

Thanks for your help!

Aucun commentaire:

Enregistrer un commentaire