Reputation: 4537
I have fit a neural net in R:
model = nnet(f1/max(f1)~n1+n2+n3+n4+n5+n6+n7+n8+n9+n10+n11+n12,data=md,size=3)
From the model object I can extract the formula of the call, model$call$formula
, which returns an object of type call
and appears to be a list of length 3. I know I can use as.formula()
on the call
object in the nnet()
call but I don't know how to edit it first.
What I want to do is modify the formula and then pass it back to nnet()
. Specifically, I'd like to be able to change the dependent variable and add or remove dependent variables.
Upvotes: 2
Views: 584
Reputation: 131
You can also do it "manually" without update.formula
.
I guess using update.formula
might be easier, but still i give you another way:
## your formula
f.example <- x ~ n1 + n2
## you can extract each member of the formula with [[2/1/3]]
f.left.side <-as.character(f.example[[2]]) # "x"
f.middle <- as.character(f.example[[1]]) # "~"
f.right.side <- as.character(f.example[[3]]) # "n1 + n2"
## you do your change, e.g:
f.right.side.new <- "n1 + n3"
## you rebuild your formula, first as a character (%s for string), then as a formula
f.new <- sprintf("%s ~ %s", f.left.side, f.right.side.new)
f.new <- as.formula(f.new)
Upvotes: 4
Reputation: 44525
You need to use update.formula
:
update.formula is used to update model formulae. This typically involves adding or dropping terms, but updates can be more general.
Here are some examples you can look at using variables from mtcars
:
f1 <- mpg ~ cyl + wt
f2 <- update(f1, . ~ . + am)
f2
## mpg ~ cyl + wt + am
f3 <- update(f2, hp ~ .)
f3
## hp ~ cyl + wt + am
f4 <- update(f3, mpg ~ hp)
f4
## mpg ~ hp
Upvotes: 4