expand a data frame from the min to the max value of each column

Viewed 403

The reproducible data below contains random values for 2 covariates (cov1 and cov2), 2 animals (Cat and Dog) and 2 seasons (Summer and Winter).

library(dplyr); library(tidyr)
set.seed(123)
dat <- data.frame(Season = rep(c("Summer", "Winter"), each = 100),
                  Species = rep(c("Cat", "Dog", "Cat", "Dog"), each = 50),
                  cov1 = sample(1:100, 200, replace = TRUE),
                  cov2 = sample(1:100, 200, replace = TRUE))

head(dat)
  Season Species cov1 cov2
1 Summer     Cat   29   24
2 Summer     Cat   79   97
3 Summer     Cat   41   61
4 Summer     Cat   89   52
5 Summer     Cat   95   41
6 Summer     Cat    5   89

I want to create a new df that contains a sequence from the min to the max value for each Season/Species combination. My initial thought was to first use dplyr to identify the the min and max values.

RangeDat <- dat %>% group_by(Season, Species) %>% 
  summarise_each(funs(min, max)) %>%
  as.data.frame()

> RangeDat
  Season Species cov1_min cov2_min cov1_max cov2_max
1 Summer     Cat        3        5      100       97
2 Summer     Dog        1        1       99       99
3 Winter     Cat        2        1       99      100
4 Winter     Dog       12        2       99      100

From here I am not sure how to expand the df. Ideally the result df would have 4 columns (Season, Species, cov1, cov2). The values for cov1 and cov2 would range from the min to the max value for each Season/Species combination. Like the initial dat df, the values for Season and Species would repeat down the df for the increasing values of cov1 and cov2.

In reference to the comments, is it possible to include an NA value where the length of a Species/Season combination is less than the 'maximum' range?

Any suggestions are greatly appreciated!

1 Answers
Related