使用“ diff”时出现错误。 dplyr mutate内部的功能 [英] Error when using "diff" function inside of dplyr mutate

查看:120
本文介绍了使用“ diff”时出现错误。 dplyr mutate内部的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将新列 更改为data.frame。当 V 列顺序从降序更改为升序时,我在 mutate内使用 diff 函数将其归类到新列 H 中。

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"))

但是出错了

Error: incompatible size (9), expecting 10 (the group size) or 1

但是当我这样做


diff(df $ V)

diff(df$V)

[1] -10 -10 -10 -10 0 10 10 10 10 0 -10 -10 -10 -10 0 10 10 10 10 10 0 -10 -10 -10 -10 0 10 10 10 10

[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

似乎在逻辑上工作。为什么在 dplyr内部执行操作时会出错?

seems to be working logically. Why I'm getting error when I do inside of dplyr?

推荐答案

我们需要再加上一个值,以使长度等于 diff 返回的长度,其长度小于组的长度。即

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"))

如果我们需要第一个值是 back,则将条件更改为< = 0

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

这篇关于使用“ diff”时出现错误。 dplyr mutate内部的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆