不明白为什么我的超前和滞后功能会忽略分组依据。 这是一个简单的示例(实际上我需要按5列分组)。
# Dummy DataSet
df <- data.frame(group = c("a","a","a","a", "a", "b", "b", "b", "b", "b"),
order = c(3, 4, 2, 5, 1, 1, 3, 4, 2, 4),
value = c(15, 22, 43, 31, 25, 11, 37, 24, 18, 9))
"group" "order" "value"
"a" 3 15
"a" 4 22
"a" 2 43
"a" 5 31
"a" 1 25
"b" 1 11
"b" 3 37
"b" 4 24
"b" 2 18
"b" 4 9
尝试过此操作,但即使按以下顺序操作也无法正常工作
df %>%
group_by(group) %>%
mutate(previous = dplyr::lag(value, n=1, default=NA, order_by = order))
然后尝试事先安排。
df %>%
arrange(group, order) %>%
group_by(group) %>%
mutate(previous = dplyr::lag(value, n=1, default=NA))
"group" "order" "value" "previous"
"a" 1 25 NA
"a" 2 43 25
"a" 3 15 43
"a" 4 22 15
"a" 5 31 22
"b" 1 11 31
"b" 2 18 11
"b" 3 37 18
"b" 4 24 37
"b" 4 9 24
固定排序,但仍忽略组的原因,因为b 1应该是NA而不是31。 是我遗漏了明显的东西还是不能将lag / lead和group_by这样组合?
可以在SQL中使用
LAG(value, 1, NULL) OVER (PARTITION BY group ORDER BY order)
抱歉,如果格式不佳,请不要在之前发布代码问题。