This post is a following up of Changing line color in ggplot based on "several factors" slope
I would like to group the data (bellow) by \"PQ\", however I get
The error is due to the difference in length from the output of diff
with respect to the original dataset. It returns one element less than the original data. So appending a 0 or NA will solve the issue
df %>%
filter(N=="N0" | N=="N1") %>%
group_by(PQ) %>%
mutate(slope = c(0, diff(Value)))
To make it compact, instead of ==
, we can use %in%
when there are multiple elements
df %>%
filter(N %in% paste0("N", 0:1)) %>%
group_by(PQ) %>%
mutate(slope = c(0, diff(Value)))
Regarding the second issue, about doing this for all the combinations in 'N', use the combn
on the unique
elements of 'N', filter
the 'N' based on the combination values, after grouping by 'PQ', calculate the diff
of 'Value'. The output will be a list
as we specified simplify = FALSE
.
combn(as.character(unique(df$N)),2, FUN = function(x) df %>%
filter(N %in% x) %>%
group_by(PQ) %>%
mutate(slope = c(0, diff(Value))), simplify = FALSE )