Error when using “diff” function inside of dplyr mutate

前端 未结 1 1994
抹茶落季
抹茶落季 2021-01-12 08:50

I try to mutate new column to data.frame. When V column order changes from decreasing to increasing order, I use diff function inside

相关标签:
1条回答
  • 2021-01-12 09:21

    We need to concatenate with one more value to make the length equal as diff returns with a length one less than the length of the group. i.e.

    length(df$V)
    #[1] 30
    length(diff(df$V))
    #[1] 29
    

    So, we concatenate with a dummy number at the beginning to make the length equal.

     df %>%
       group_by(gr) %>%
       mutate(H=ifelse(c(0,diff(V))<0,"back","forward"))
    

    If we need the first value to be 'back', change the condition to <=0

    0 讨论(0)
提交回复
热议问题