我有这个数据框:
data <- data.frame(
ID = c(111, 111, 111,111, 333, 333, 333,333),
planes = c(2, 2, 3, 3, 4, 4, 5, 5),
origin = c(3, 3, 6, 8, 5, 5, 7, 9),
destination = c(9, 9, 10, 20, 11, 11, 13, 25)
)
我想按 ID 和具有相同出发地和目的地的飞机对数据进行分组。飞机值 2 和 4 具有相同的出发地和目的地,我想保留它们并过滤掉其余的。
我的输出应该如下所示:
ID planes origin destination
111 2 3 9
111 2 3 9
333 4 5 11
333 4 5 11
您可以使用 dplyr 进行过滤
data %>%
filter(n()>1, .by=everything())
我们使用
by=
创建组,然后使用 n()
给出每个组的数量,这样我们只保留具有超过 1 个值的组。
您不需要为此循环。
library(dplyr)
data |>
add_count(planes, ID, destination) |>
filter(n > 1)
# ID planes origin destination n
# 1 111 2 3 9 2
# 2 111 2 3 9 2
# 3 333 4 5 11 2
# 4 333 4 5 11 2
来自文档:
可让您快速计算一个或多个变量的唯一值:count()
大致相当于df %>% count(a, b)
。df %>% group_by(a, b) %>% summarise(n = n())
和add_count()
相当于add_tally()
和count()
,但使用tally()
而不是mutate()
,以便它们添加具有分组计数的新列。summarise()
您可以使用 ave
和 subset
按 ID 和 planes 对
origin和
destination进行分组,因为
diff
erences 为零。
> subset(data, ave(origin, ID, planes, FUN=diff) == 0 &
+ ave(destination, ID, planes, FUN=diff) == 0)
ID planes origin destination
1 111 2 3 9
2 111 2 3 9
5 333 4 5 11
6 333 4 5 11