Suppose we have the following dataset in 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))
I would like to produce the following table:
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
In this table, the data is summarized by "Type." Column "MinValue1" is the minimal value for a particular type and column "MinValue2" is the minimal value of "Value2", given the minimal value(s) of column "Value1". Columns Mean* are the general average of all observations.
One way to do this is to implement loops that iterate over each type and do the math. However, I am looking for a better/easy/beautiful way to perform such operation.
I have played with tools from "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
Note that we have not Column "MinValue2" here. Also note that "summarise(..., MinValue2 = min(Value2), ...)" does not work since this solution takes the minimum of all observations of one type.
We may play with "slice" and then merge the results:
> 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
but note that the "slice" tool does not help us here: "Type A, Value1 5" should have "Value2" == 3, not == 4 as slice returns.
So, have you guys an elegant way to achieve the results I seek? Thanks!