I try to mutate
new column to data.frame. When V
column order changes from decreasing to increasing order, I use diff
function inside of mutate
to categorize them in new column H
.
V <- c(seq(30,-10,-10),seq(-10,30,10))
gr = rep(seq(1,3),each=10)
df <- data.frame(V,gr)
library(dplyr)
diff_df <- df%>%
group_by(gr)%>%
mutate(H=ifelse(diff(V)<0,"back","forward"))
However getting error
Error: incompatible size (9), expecting 10 (the group size) or 1
But when I do
diff(df$V)
[1] -10 -10 -10 -10 0 10 10 10 10 0 -10 -10 -10 -10 0 10 10 10 10 0 -10 -10 -10 -10 0 10 10 10 10
seems to be working logically. Why I'm getting error when I do inside of dplyr?