'returning min and max from two matrix with conditions

I'm trying to automate a process in R, but I still can't get to what I need. I have two matrix, one matrix represent the incidence of species that occur in samples and the other matrix represents environmental variables of these samples.

I need the minimum and maximum of environmental variables to be returned according to two conditions, the maximum or minimum returned has to search for samples and group by species.

All available packages and scripts that I've checked don't do what I need, does anyone have any ideas?

Thanks.

Example:

set.seed(1)
> y <- matrix(sample(c(9: 99), 6, replace=TRUE),
+                  nrow = 3,
+                  ncol = 2,
+                  dimnames = list(c("site1", "site2", "site3"),
+                                  c("env1", "env2")))
> y
      env1 env2
site1   76   42
site2   47   95
site3    9   51
> x <- matrix(sample(c(0,1), 9, replace=TRUE),
+                            nrow = 3,
+                            ncol = 3,
+                            dimnames = list(c("site1", "site2", "site3"),
+                                            c("sp.a", "sp.b", "sp.c")))
> x
      sp.a sp.b sp.c
site1    1    0    0
site2    1    0    1
site3    0    0    1
>  output <- matrix(sample(c(1:99), 12, replace=TRUE),
+             nrow = 3,
+             ncol = 4,
+             dimnames = list(c("sp.a", "sp.b", "sp.c"),
+                             c("max.var1", "min.var1", "max.var2", "min.var2")))
> output
     max.var1 min.var1 max.var2 min.var2
sp.a       74       79       89       89
sp.b        7       85       37       44
sp.c       73       37       34       79
> 


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source