Bury
Bury

Reputation: 567

Add formula into function

I have this example data

    install.packages('neuralnet')
    library(neuralnet)    
    DV<-runif(20,min=-3,max=3)
    RV_1<-runif(20,min=-3,max=3)
    RV_2<-runif(20,min=-3,max=3)
    formula<-'RV_1+RV_2'
    df<-data.frame(DV=DV,RV_1=DV_1,RV2=RV_2)

and I learn the neural network this way

neuralnet(DV~RV_1+RV_2,data=df,hidden=5)

and everything works well.

But if I need to use it in function for more combinations I need to use it like

testfun<-function(x,y){
  nnet<<-neuralnet(x~y,data=df,hidden=5)
}
testfun(DV,formula)

Which doesn't work I've tried these approaches

testfun<-function(x,y){
  nnet<<-neuralnet(print(x,quote=FALSE)~print(y,quote=FALSE),data=df,hidden=5)
}

or

testfun<-function(x,y){
  nnet<<-neuralnet(as.symbol(x)~as.symbol(y),data=df,hidden=5)
}

or

testfun<-function(x,y){
  nnet<<-neuralnet(get(x)~get(y),data=df,hidden=5)
}

But nothing works. The problem is that I cannot change the formula object and I still cannot go trough.

Any advices how to solve this problem?

Upvotes: 0

Views: 67

Answers (1)

Vlo
Vlo

Reputation: 3188

Try this?

testfun<-function(x,y) {
    neuralnet(as.formula(paste(x, "~", y, sep ="")), data=df, hidden=5)
}

nnet <- testfun("var1", "var2")

Upvotes: 2

Related Questions