-2

Hi this is an excel form of data i want to be able to create in R

1

Just want to make it clear, I need to be able to make the column Group_fix equal to 5 for the next 12 months period observation, every time an observation date has 5 in its Group column.

How to make it possible in R? Can we use ifelse function?

R04
  • 1
  • 2
  • 3
    Please edit as shown [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – NelsonGon May 05 '20 at 15:14

1 Answers1

0

Here is an approach with lag from dplyr.

library(dplyr)
data %>% 
  mutate(GroupFix = case_when(Group == 5 |
                              lag(Group,2) == 5 |
                              lag(Group,2) == 5 |
                              lag(Group,3) == 5 |
                              lag(Group,4) == 5 |
                              lag(Group,5) == 5 |
                              lag(Group,6) == 5 |
                              lag(Group,7) == 5 |
                              lag(Group,8) == 5 |
                              lag(Group,9) == 5 |
                              lag(Group,10) == 5 |
                              lag(Group,11) == 5  ~ 5,
                              TRUE ~ as.numeric(Group)))
   Observation.Date Group GroupFix
1          12/31/19     1        1
2           1/31/20     2        2
3           2/29/20     2        2
4           3/31/20     2        2
5           4/30/20     3        3
6           5/31/20     4        4
7           6/30/20     5        5
8           7/31/20     5        5
9           8/31/20     4        5
10          9/30/20     3        5
11         10/31/20     2        5
12         11/30/20     3        5
13         12/31/20     4        5
14          1/31/21     5        5
15          2/28/21     5        5
16          3/31/21     4        5
17          4/30/21     3        5
18          5/31/21     2        5
19          6/30/21     1        5
20          7/31/21     1        5
21          8/31/21     1        5
22          9/30/21     1        5
23         10/31/21     1        5
24         11/30/21     1        5
25         12/31/21     1        5
26          1/31/22     1        5
27          2/28/22     1        1

Data

data <- structure(list(Observation.Date = structure(c(8L, 1L, 13L, 14L, 
16L, 18L, 20L, 22L, 24L, 26L, 4L, 6L, 9L, 2L, 11L, 15L, 17L, 
19L, 21L, 23L, 25L, 27L, 5L, 7L, 10L, 3L, 12L), .Label = c("1/31/20", 
"1/31/21", "1/31/22", "10/31/20", "10/31/21", "11/30/20", "11/30/21", 
"12/31/19", "12/31/20", "12/31/21", "2/28/21", "2/28/22", "2/29/20", 
"3/31/20", "3/31/21", "4/30/20", "4/30/21", "5/31/20", "5/31/21", 
"6/30/20", "6/30/21", "7/31/20", "7/31/21", "8/31/20", "8/31/21", 
"9/30/20", "9/30/21"), class = "factor"), Group = c(1L, 2L, 2L, 
2L, 3L, 4L, 5L, 5L, 4L, 3L, 2L, 3L, 4L, 5L, 5L, 4L, 3L, 2L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA, 
-27L))
Ian Campbell
  • 23,484
  • 14
  • 36
  • 57