我有一个数据框,如:
df <- data.frame(id = c('1', '2', '3', '4', '5', '6', '7', '8', '9', '10'), Date = c("01-Feb-17", "05-Feb-17", "01-May-17", "03-May-17","24-May-17", "05-Oct-17", "20-Oct-17", "25-Oct-17", "01-Dec-17", "12-Dec-17"), Name=c("John", "Jack", "Jack", "John", "John", "Jack", "John", "Jack", "John", "Jack"), Workout=c('150', '130', '140', '160', '150', '130', '140', '160', '150', '130'))
现在我想在下一个日期的每个名字的Workout列中移动值。
例如:
等。
重视“杰克”同样的行动
答案 0 :(得分:2)
df <- data.frame(id = c('1', '2', '3', '4', '5', '6', '7', '8', '9', '10'),
Date = c("01-Feb-17", "05-Feb-17", "01-May-17", "03-May-17","24-May-17", "05-Oct-2017", "20-Oct-17", "25-Oct-17", "01-Dec-2017", "12-Dec-2017"),
Name=c("John", "Jack", "Jack", "John", "John", "Jack", "John", "Jack", "John", "Jack"),
Workout=c('150', '130', '140', '160', '150', '130', '140', '160', '150', '130'))
library(dplyr)
df %>%
group_by(Name) %>% # for every name
mutate(Workout = lag(Workout)) %>% # replace value with the previous one
ungroup() # forget the grouping
# # A tibble: 10 x 4
# id Date Name Workout
# <fct> <fct> <fct> <fct>
# 1 1 01-Feb-17 John NA
# 2 2 05-Feb-17 Jack NA
# 3 3 01-May-17 Jack 130
# 4 4 03-May-17 John 150
# 5 5 24-May-17 John 160
# 6 6 05-Oct-2017 Jack 140
# 7 7 20-Oct-17 John 150
# 8 8 25-Oct-17 Jack 130
# 9 9 01-Dec-2017 John 140
#10 10 12-Dec-2017 Jack 160
我假设您的数据集将按照示例中的Date
进行排序。如果没有,您可以使用arrange
功能进行订购。