Reputation: 1073
How can i get the previous value of each group in a new column C
and the starting value for each group will be empty as it does not have previous value of respective group!
Can dplyr can perform this?
Code:
df <- data.frame(A = c('a1','a1','b1','b1','b1','c2','d2','d2'),
B = c("2017-02-20","2018-02-14","2017-02-06","2017-02-27","2017-02-29","2017-02-28","2017-02-09","2017-02-10"))
Dataframe:
A B
a1 2017-02-20
a1 2018-02-14
b1 2017-02-06
b1 2017-02-27
b1 2017-02-29
c2 2017-02-28
d2 2017-02-09
d2 2017-02-10
Expected Output
A B C
a1 2017-02-20
a1 2018-02-14 2017-02-20
b1 2017-02-06
b1 2017-02-27 2017-02-06
b1 2017-02-29 2017-02-27
c2 2017-02-28
d2 2017-02-09
d2 2017-02-10 2017-02-09
Upvotes: 0
Views: 390
Reputation: 2368
You could use the lag
function from dplyr
:
df <- data.frame(A = c('a1','a1','b1','b1','b1','c2','d2','d2'),
B = c("2017-02-20","2018-02-14","2017-02-06",
"2017-02-27","2017-02-29","2017-02-28",
"2017-02-09","2017-02-10"))
library(dplyr)
df %>%
group_by(A) %>%
mutate(C = lag(B, 1, default = NA))
This will apply the lag function for each group of "A"
Output:
# A tibble: 8 x 3
# Groups: A [4]
A B C
<fct> <fct> <fct>
1 a1 2017-02-20 NA
2 a1 2018-02-14 2017-02-20
3 b1 2017-02-06 NA
4 b1 2017-02-27 2017-02-06
5 b1 2017-02-29 2017-02-27
6 c2 2017-02-28 NA
7 d2 2017-02-09 NA
8 d2 2017-02-10 2017-02-09
Upvotes: 1