R - 使用最小函数聚合变量并查找与最小值相关的索引
R - Aggregate variables with min function and find index related to the min value
我有一个包含 3 列(ID、位置、值)的数据框。
每个 ID 有多个 Positions 和 Values。我想为每个 ID 获取最小值 Value ,并且在同一个聚合中,获取值最小的位置。
例如:
Data <- data.frame(c("A","A","A","B","B"),c(10,2,4,1,6),c(0,5,4,3,1))
colnames(Data) <- c("ID","Position","Value")
# The result would be :
Data_min <- data.frame(c("A","B"),c(10,6),c(0,1))
# Aggregate function helps me getting the min value per ID :
aggregate (Data$Value, list(Data$ID), min)
但我还没有找到如何获得与最小值相关的位置。
我可以使用 which
函数来查找最小值,但我很确定有一种更聪明的方法可以做到这一点。
是这样的吗?
df = Data %>%
group_by(ID) %>%
summarize(Position=Position[Value==min(Value)],
Value=min(Value))
考虑 ave
子集数据帧和 return 对应 Value 匹配的所有行:
Data[Data$Value == ave(Data$Value, Data$ID, FUN=min),]
# ID Position Value
# 1 A 10 0
# 5 B 6 1
@Antonis summarise
答案的另一种方法是将此问题作为过滤过程来处理:
Data <- data.frame(c("A","A","A","B","B"),c(10,2,4,1,6),c(0,5,4,3,1))
colnames(Data) <- c("ID","Position","Value")
library(dplyr)
Data %>%
group_by(ID) %>%
filter(Value == min(Value)) %>%
ungroup()
# # A tibble: 2 x 3
# ID Position Value
# <fct> <dbl> <dbl>
# 1 A 10.0 0
# 2 B 6.00 1.00
我有一个包含 3 列(ID、位置、值)的数据框。 每个 ID 有多个 Positions 和 Values。我想为每个 ID 获取最小值 Value ,并且在同一个聚合中,获取值最小的位置。
例如:
Data <- data.frame(c("A","A","A","B","B"),c(10,2,4,1,6),c(0,5,4,3,1))
colnames(Data) <- c("ID","Position","Value")
# The result would be :
Data_min <- data.frame(c("A","B"),c(10,6),c(0,1))
# Aggregate function helps me getting the min value per ID :
aggregate (Data$Value, list(Data$ID), min)
但我还没有找到如何获得与最小值相关的位置。
我可以使用 which
函数来查找最小值,但我很确定有一种更聪明的方法可以做到这一点。
是这样的吗?
df = Data %>%
group_by(ID) %>%
summarize(Position=Position[Value==min(Value)],
Value=min(Value))
考虑 ave
子集数据帧和 return 对应 Value 匹配的所有行:
Data[Data$Value == ave(Data$Value, Data$ID, FUN=min),]
# ID Position Value
# 1 A 10 0
# 5 B 6 1
@Antonis summarise
答案的另一种方法是将此问题作为过滤过程来处理:
Data <- data.frame(c("A","A","A","B","B"),c(10,2,4,1,6),c(0,5,4,3,1))
colnames(Data) <- c("ID","Position","Value")
library(dplyr)
Data %>%
group_by(ID) %>%
filter(Value == min(Value)) %>%
ungroup()
# # A tibble: 2 x 3
# ID Position Value
# <fct> <dbl> <dbl>
# 1 A 10.0 0
# 2 B 6.00 1.00