按 dplyr 中的另一列过滤分组数据集
Filter Grouped Dataset by Another Column in dplyr
我有一个包含同一个人多行的数据集
set.seed(420)
df <- data.frame(ind = c(rep("A",3), rep("B",5), rep("C",4)), value = seq(1:12), location = sample(c("first", "second", "third"), 12, replace = TRUE))
df
ind value location
1 A 1 first
2 A 2 first
3 A 3 second
4 B 4 second
5 B 5 first
6 B 6 first
7 B 7 first
8 B 8 first
9 C 9 first
10 C 10 first
11 C 11 first
12 C 12 third
我想为每个ind
个人找到 value
列最高的 location
。
所以最终的数据集是:
ind value location
A 3 second
B 8 first
C 12 third
这可能与 dplyr
中的 group_by
和 summarize
或 mutate
相关吗?
有几种方法可以使用 tidyverse
。
library(tidyverse)
df %>% group_by(ind) %>% slice_max(value)
或者
df %>% group_by(ind) %>% filter(value == max(value))
解决您的问题
变异()
对于mutate()
,需要额外的步骤来过滤数据(即使数据唯一),因为它不会按组收缩数据。
- 像往常一样先
group_by
,
- 确保我们按值
arrange
,因为我们将使用该位置来提取与最大值 关联的location
- 将
value
列设置为 max(value)
- 将
location
列设置为 last(location)
,因为我们已经对 value
进行了排序,last(location)
应该是 [=21] 的 location
=]
- 只保留
distinct
行
df %>% group_by(ind) %>%
arrange(value) %>%
mutate(value = max(value),
location = last(location)) %>%
distinct(value, .keep_all = T)
总结()
mutate()
中的类似逻辑可以应用于 summarise()
,但我们不需要 distinct()
步骤,因为 summarise()
会自然地按组收缩数据, 但请记住我们需要 arrange(value)
来确保值正确排序。
df %>% group_by(ind) %>%
arrange(value) %>%
summarize(value = max(value), location = last(location))
输出
# A tibble: 3 x 3
# Groups: ind [3]
ind value location
<chr> <int> <chr>
1 A 3 second
2 B 8 first
3 C 12 third
我有一个包含同一个人多行的数据集
set.seed(420)
df <- data.frame(ind = c(rep("A",3), rep("B",5), rep("C",4)), value = seq(1:12), location = sample(c("first", "second", "third"), 12, replace = TRUE))
df
ind value location
1 A 1 first
2 A 2 first
3 A 3 second
4 B 4 second
5 B 5 first
6 B 6 first
7 B 7 first
8 B 8 first
9 C 9 first
10 C 10 first
11 C 11 first
12 C 12 third
我想为每个ind
个人找到 value
列最高的 location
。
所以最终的数据集是:
ind value location
A 3 second
B 8 first
C 12 third
这可能与 dplyr
中的 group_by
和 summarize
或 mutate
相关吗?
有几种方法可以使用 tidyverse
。
library(tidyverse)
df %>% group_by(ind) %>% slice_max(value)
或者
df %>% group_by(ind) %>% filter(value == max(value))
解决您的问题
变异()
对于mutate()
,需要额外的步骤来过滤数据(即使数据唯一),因为它不会按组收缩数据。
- 像往常一样先
group_by
, - 确保我们按值
arrange
,因为我们将使用该位置来提取与最大值 关联的 - 将
value
列设置为max(value)
- 将
location
列设置为last(location)
,因为我们已经对value
进行了排序,last(location)
应该是 [=21] 的location
=] - 只保留
distinct
行
location
df %>% group_by(ind) %>%
arrange(value) %>%
mutate(value = max(value),
location = last(location)) %>%
distinct(value, .keep_all = T)
总结()
mutate()
中的类似逻辑可以应用于 summarise()
,但我们不需要 distinct()
步骤,因为 summarise()
会自然地按组收缩数据, 但请记住我们需要 arrange(value)
来确保值正确排序。
df %>% group_by(ind) %>%
arrange(value) %>%
summarize(value = max(value), location = last(location))
输出
# A tibble: 3 x 3
# Groups: ind [3]
ind value location
<chr> <int> <chr>
1 A 3 second
2 B 8 first
3 C 12 third