如何基于两列对数据框进行子集化?

问题描述 投票:0回答:3

我有这个数据框:

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
r subset
3个回答
1
投票

您可以使用 dplyr 进行过滤

data %>% 
   filter(n()>1, .by=everything())

我们使用

by=
创建组,然后使用
n()
给出每个组的数量,这样我们只保留具有超过 1 个值的组。


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()
,以便它们添加具有分组计数的新列。


1
投票

您可以使用 avesubsetIDplanes

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
© www.soinside.com 2019 - 2024. All rights reserved.