0

I am trying to calibrate a model and I need to vary some parameters to see how the output behaves. To do that I would like to create a data frame where each row is one set of parameters.
An example data set:

pars <- data.frame(a=3, b=4, c=5)

Vary the parameter a:

dfa <- data.frame(a = 1:6)

Then try to join it in a new data frame:

bind_cols(dfa, pars[rep(seq_len(nrow(pars)), each=length(a)),])  

The same process goes for b.

dfb <- data.frame(b = 3:6)

dfb <- 
  bind_cols(dfb, pars[rep(seq_len(nrow(pars)), each=length(dfb$b)),]) %>% 
  select(-c(b1))

bind_rows(dfa,dfb)

This is not a very effective way for a model of around 30 parameters. I am guessing this should be put into a loop of some sort. I am probably not the first person trying to do this, so I would appreciate some help if someone has already done this. Some answers to similar problems are this and I have used this as a part of my attempt. This comment is also interesting because I have a varying number of rows to repeat:

n.times <- c(2,4) ; df[rep(seq_len(nrow(df)), n.times),] 

Any help on this is appreciated.

m_c
  • 496
  • 2
  • 19
  • 3
    Check out base function `?expand.grid`. – Rui Barradas Jul 13 '19 at 20:32
  • i did, and I have used it before, but it gives me all possible combinations of the parameters which I don't want. https://mladencucak.github.io/AnalysisPLBIreland/Analysis.html#the_analysis – m_c Jul 14 '19 at 02:05
  • 2
    It's not clear to me what you're looking for. Your code seems to copy the previous iteration once for each variety of the new variable. For 30 variables, even if they each only have two values, won't that lead to 2^30, or over 1 billion different combinations? – Jon Spring Jul 14 '19 at 05:52

1 Answers1

1

Since R fills columns by default, all you need for your first two examples is

data.frame(dfa, pars)
#   a a.1 b c
# 1 1   3 4 5
# 2 2   3 4 5
# 3 3   3 4 5
# 4 4   3 4 5
# 5 5   3 4 5
# 6 6   3 4 5
data.frame(dfb, pars)
#   b a b.1 c
# 1 3 3   4 5
# 2 4 3   4 5
# 3 5 3   4 5
# 4 6 3   4 5

Since your model does not use a.1 or b.1 you don't have to exclude them but adding [, -2] to the first one and [, -3] would take care of that.

dcarlson
  • 10,936
  • 2
  • 15
  • 18