假设我们在 R 中有以下数据集:
> td
Type Rep Value1 Value2
1 A 1 7 1
2 A 2 5 4
3 A 3 5 3
4 A 4 8 2
5 B 1 5 10
6 B 2 6 1
7 B 3 7 1
8 C 1 8 13
9 C 2 8 13
> td <- structure(list(Type = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
3L, 3L), .Label = c("A", "B", "C"), class = "factor"), Rep = c(1L,
2L, 3L, 4L, 1L, 2L, 3L, 1L, 2L), Value1 = c(7L, 5L, 5L, 8L, 5L,
6L, 7L, 8L, 8L), Value2 = c(1L, 4L, 3L, 2L, 10L, 1L, 1L, 13L,
13L)), .Names = c("Type", "Rep", "Value1", "Value2"), class = "data.frame",
row.names = c(NA, -9L))
我想制作下表:
Type MinValue1 MinValue2 MeanValue1 MeanValue2
1 A 5 3 6.25 2.5
2 B 5 10 6.00 4.0
3 C 3 13 8.00 13.0
在此表中,数据按“类型”汇总。列“MinValue1”是特定类型的最小值,列“MinValue2”是“Value2”的最小值,给定列“Value1”的最小值。列平均值*是所有观察值的一般平均值。
一种方法是实现对每种类型进行迭代并进行数学运算的循环。但是,我正在寻找一种更好/简单/漂亮的方式来执行此类操作。
我玩过“tidyverse”中的工具:
> library(tidyverse)
> td %>%
group_by(Type) %>%
summarise(MinValue1 = min(Value1),
MeanValue1 = mean(Value1),
MeanValue2 = mean(Value2))
# A tibble: 3 × 4
Type MinValue1 MeanValue1 MeanValue2
<fctr> <int> <dbl> <dbl>
1 A 5 6.25 2.5
2 B 5 6.00 4.0
3 C 8 8.00 13.0
请注意,我们这里没有“MinValue2”列。另请注意,“summarise(..., MinValue2 = min(Value2), ...)”不起作用,因为此解决方案采用一种类型的所有观察值中的最小值。
我们可以玩“切片”,然后合并结果:
> td %>% group_by(Type) %>% slice(which.min(Value1))
Source: local data frame [3 x 4]
Groups: Type [3]
Type Rep Value1 Value2
<fctr> <int> <int> <int>
1 A 3 5 4
2 B 1 5 10
3 C 1 8 13
但请注意,“切片”工具在这里对我们没有帮助:“类型 A,Value1 5”应该具有“Value2”== 3,而不是切片返回时的 == 4。
那么,你们有没有一种优雅的方式来实现我所寻求的结果?谢谢!