使用后我想要的一列summarise()是(两个)值之间的差异。在 m 的情况下,每个组总是会有两行或更少的行。我在网上找到的功能是diff(). 但是,我遇到了一个问题。看这个例子:
df <- data.frame(value = runif(198),
id = c(
sample(1:100, 99),
sample(1:100, 99))
)
find <- df %>%
group_by(id) %>%
summarise(count = n()) %>%
filter(count != 2)
find
在这种情况下,由于我没有使用diff(),所以我得到了这个:
> find
# A tibble: 2 x 2
id count
<int> <int>
1 14 1
2 39 1
它工作正常。现在,如果我包括diff():
> find <- df %>%
+ group_by(id) %>%
+ summarise(diference = diff(value), count = n()) %>%
+ filter(count != 2)
`summarise()` regrouping output by 'id' (override with `.groups` argument)
> find
# A tibble: 0 x 3
# Groups: id [0]
# … with 3 variables: id <int>, diference <dbl>, count <int>
它什么都没有。如果我不过滤(这是一个相对较短的数据框,所以我一个接一个),我看到那些行消失了。在一个较短的示例中,它将是:
> df <- data.frame(value = runif(10),
+ id = c(
+ sample(1:6, 5),
+ sample(1:6, 5))
+ )
> find <- df %>%
+ group_by(id) %>%
+ summarise(diference = diff(value), count = n())
`summarise()` regrouping output by 'id' (override with `.groups` argument)
> find
# A tibble: 4 x 3
# Groups: id [4]
id diference count
<int> <dbl> <int>
1 2 -0.309 2
2 3 0.474 2
3 4 -0.148 2
4 6 0.291 2
如您所见,1and 5rows (id) 消失了。我相信 apllyingdiff()会导致它,因为没有它,这不会发生:
> find <- df %>%
+ group_by(id) %>%
+ summarise(count = n())
`summarise()` ungrouping output (override with `.groups` argument)
> find
# A tibble: 6 x 2
id count
<int> <int>
1 1 1
2 2 2
3 3 2
4 4 2
5 5 1
6 6 2
那是完全相同的数据。
但是,如果我手动执行此操作,diff()则会给我一个输出,尽管方式略有不同:
> diff(5)
numeric(0)
> diff(c(5, 4))
[1] -1
那么,我的问题是,是否有更好的功能可以做到这一点,或者只是某种方式让我在不擦除单项组的情况下获得输出,如下所示:
id count diference
1 1 1 1
2 58 1 58
我知道差异将与 id 相同,但我对此感兴趣的原因是因为这只是我将提出的论点之一filter()。它将是:(filter(diference != 0 || count != 2)再一次,这不是我的原始数据)。