Say I have I fit an nls
model to some data, d
, in R.
#fake data
x<- seq(1,10,by=0.1)
y<- 1*(x / (2 + x))
y<- y + rnorm(0, 0.05, n =length(y))
d<- data.frame(x,y)
#fit the nls model
model <- nls(y ~ v1*(x/(v2 + x)), start=c(v1=0.9,v2=2.1))
I want to return from the model
object the name of the data frame ( d
), and the name of the dependent varaible ( y
).
You can get these values from the model object as follows:
# Data frame name
as.character(model$data)
# Dependent variable name
as.character(formula(model)[2])
How did I know that, you ask? Well, I didn't, but you can often figure out things like this by looking at the structure of the model object (type str(model)
in the console) returned by an R function.
For example, in this case, model
is a list with six elements. The first element, called m
is itself a list. Here are the first few lines of output:
str(model)
List of 6 $ m :List of 16 ..$ resid :function () ..$ fitted :function () ..$ formula :function ()
Note that one of the elements of m
is called formula
and it's a function. So, I tried typing formula(model)
in the console and got this:
y ~ v1 * (x/(v2 + x))
Then I typed str(formula(model))
to see what kind of object formula()
was actually returning:
Class 'formula' length 3 y ~ v1 * (x/(v2 + x)) ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
Notice that it returns an object with three elements ( length 3
). The second element happens to contain the dependent variable name. Wrapping it in as.character
changes it into a string, which is what I assume you want.
Now for the data frame. Note that one of the list elements returned by str(model)
is called data
. So I typed model$data
in the console and got this:
d
Once again, I wrapped it in as.character
to turn the output into a string.
There may be better ways to approach this, but don't underestimate what you can accomplish just by poking around inside the object returned by a function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.