0

I'm trying to automate this one part of my R script, but I can't figure out how. Essentially, I have this code:

  currentmatrix <- datas[,,i]
  data <- as.data.frame(currentmatrix)
  #mod #
  colnames(data) <- c("in1","in2","in3","in4","in5","in6", "in7", "in8", "in9", "in10", "out") #change depending on number of inputs and add to nnet training
  
  #mod #
  nnet <- neuralnet(out~in1+in2+in3+in4+in5+in6+in7+in8+in9+in10, data, hidden=hidden, threshold = threshold, stepmax = 10^7,err.fct = "ce",linear.output = F,likelihood = T)
  

Now, where I have "in1","in2" etc, I'd like this to be a variable, so that I can simply reference neuralnet(var,data,hidden=hidden,...), instead of typing out the inputs to the function each time I want to change the number of inputs. I'd like, for example, to have a function f for which f(x) creates x strings named in[x], and then I could write colnames(data) <- c(f(x)) and nnet <- neuralnet(out~f_sum,...) or something similar.

Is there a way to do this? Thanks!

1 Answers1

2

You can use reformulate which returns a formula object.

formula <- reformulate(paste0('in', 1:10), 'out')
formula
#out ~ in1 + in2 + in3 + in4 + in5 + in6 + in7 + in8 + in9 + in10

You can also use column names to generate formula.

formula <- reformulate(names(data)[1:10], 'out')

this can be used in neuralnet function.

nnet <- neuralnet(formula, data, hidden=hidden, threshold = threshold, 
                   stepmax = 10^7,err.fct = "ce",linear.output = F,likelihood = T)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    That works so well for the `neuralnet` input, thank you! Is there something similar that can be done for the `colnames(data)` line? It's completely fine if it's another block of code like above. –  Jul 09 '20 at 05:52
  • You can use `colnames(data) <- c(paste0('in', 1:10), 'out')` – Ronak Shah Jul 09 '20 at 05:54
  • 1
    It works beautifully, thank you! I need to test it out a bit more but I think this is the solution :). –  Jul 09 '20 at 06:02