No need to use dplyr
here.
Data$Countries <- Countries[c(1, cumsum(diff(Data$Date) <= 0) + 1)]
Question
I can answer this question using a loop, I would like to do it without (preferably in dplyr or plyr).
I have a dataframe and a list of countries
Data <- data.frame(
Date = c(2012:2014,2014,2013:2014),
Value = rnorm(6),
)
Countries <- c("AUS","USA","UK")
The data frame looks like this
Date Value
1 2012 0.20200445
2 2013 1.75576426
3 2014 -0.67385232
4 2014 2.36476344
5 2013 -2.00068346
6 2014 -0.01290928
I need to allocate the country list to the data. The rule for application is -- keep applying the same country until the difference between two adjacent dates in the data frame is <= 0. The finished product should look like this
Date Value Countries
1 2012 0.64706706 AUS
2 2013 0.26878534 AUS
3 2014 -0.07091867 AUS
4 2014 0.49546373 USA
5 2013 -0.18158935 UK
6 2014 -0.43114076 UK
Solution
No need to use dplyr
here.
Data$Countries <- Countries[c(1, cumsum(diff(Data$Date) <= 0) + 1)]