0

I'd like to aggregate my dataset considering the interations between two factors (fac1, fac2) and apply a function for this. For example, consider the dataset given by

set.seed(1)
test <- data.frame(fac1 = sample(c("A", "B", "C"), 30, rep = T), 
                   fac2 = sample(c("a", "b"), 30, rep = T), 
                   value = runif(30))

For fac1 == "A" and "fac2 == a" we have five values and I'd like to aggregate by min. Using brutal force I tried this way

min(test[test$fac1 == "A" & test$fac2 == "a", ]$value)
Wagner Jorge
  • 430
  • 3
  • 15

2 Answers2

2

You mention aggregate and that will work here.

aggregate(test$value, test[,1:2], min)
  fac1 fac2          x
1    A    a 0.32535215
2    B    a 0.14330438
3    C    a 0.33239467
4    A    b 0.33907294
5    B    b 0.08424691
6    C    b 0.24548851
G5W
  • 36,531
  • 10
  • 47
  • 80
1

Here is a tidyverse alternative

test %>% group_by(fac1, fac2) %>% summarise(x = min(value))
## A tibble: 6 x 3
## Groups:   fac1 [?]
#  fac1  fac2       x
#  <fct> <fct>  <dbl>
#1 A     a     0.325
#2 A     b     0.339
#3 B     a     0.143
#4 B     b     0.0842
#5 C     a     0.332
#6 C     b     0.245
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68