I have a data frame like so
Number Type Time
4 B 10
5 B 11
5 B 9
1 B 8
8 R 7
3 R 9
4 R 5
4 R 5
Where I have grouped by Type and would like to make a new column called "Adjusted_Time" That contains the time of the Number before, the final Df would look like this
Number Type Time Adjusted_Time
4 B 10 8
5 B 11 10
6 B 9 11
3 B 8 N/A
8 R 7 9
7 R 9 5
6 R 5 5
5 R 5 N/A
Where the N/A goes whenever there isn't a number directly below that number. I would like to use dplyr for this Right now I have
df %>% group_by(Type) %>% Mutate(Adjusted_Time = ....)
df %>%
group_by(Type) %>%
arrange(Number) %>%
mutate(Adjusted_Time = lag(Time)) %>%
arrange(Adjusted_Time)
The function you are looking for is lag
df %>% group_by(Type) %>% arrange(Number) %>% mutate(Adjusted_Time = lag(Time))
Source: local data frame [8 x 4]
Groups: Type
Number Type Time Adjusted_Time
1 1 B 8 NA
2 4 B 10 8
3 5 B 11 10
4 5 B 9 11
5 3 R 9 NA
6 4 R 5 9
7 4 R 5 5
8 8 R 7 5
For more information see:
http://cran.r-project.org/web/packages/dplyr/vignettes/window-functions.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.