I have defined the following function:
fr<-function(x) {
u<-x[1]
v<-x[2]
sqrt(sum((plnorm(c(3,6),u,v)-c(.55,.85))^2))
}
which I then solve using optim
y<-optim(c(1,1),fr)
> y$par
[1] 1.0029771 0.7610545
This works fine.
Now I want to use these two steps on a dataframe:
mydat<-data.frame(d1=c(3,5),d2=c(6,10),p1=c(.55,.05),p2=c(.85,.35))
> mydat
d1 d2 p1 p2
1 3 6 0.55 0.85
2 5 10 0.05 0.35
where for each row in mydat, I append the two parameter resulting from
optim into mydat.
I want to do this for a larger dataset but thought I would start with a
simple two row dataframe.
I have tried this with loops and the apply function, but seem to be
getting nowhere.
Thanks for any input.
mike
mmpapenf at wisc.edu
Michael Papenfus <mmpapenf <at> wisc.edu> writes:> > I have defined the following function: > > fr<-function(x) { > u<-x[1] > v<-x[2] > sqrt(sum((plnorm(c(3,6),u,v)-c(.55,.85))^2)) > } > which I then solve using optim > y<-optim(c(1,1),fr) > > > y$par > [1] 1.0029771 0.7610545 > This works fine. > > Now I want to use these two steps on a dataframe: > mydat<-data.frame(d1=c(3,5),d2=c(6,10),p1=c(.55,.05),p2=c(.85,.35)) > > mydat > d1 d2 p1 p2 > 1 3 6 0.55 0.85 > 2 5 10 0.05 0.35 > > where for each row in mydat, I append the two parameter resulting from > optim into mydat. > I want to do this for a larger dataset but thought I would start with a > simple two row dataframe. >I would prefer a loop in this case. fr<-function(x) { sqrt(sum((plnorm(c(3,6),x[1],x[2])-c(x[3],x[4]))^2)) } y<-optim(c(1,2,0.55,0.85),fr) mydat<-data.frame(d1=c(1,0.5),d2=c(1,0.1),p1=c(.55,.05),p2=c(.85,.35)) myres<-mydat # simple way to allocate dataframe for results names(myres) = paste("res",names(myres),sep=".") for (i in 1:nrow(mydat)){ y <- optim(mydat[i,1:4],fr) myres[i,] <- y$par } mydat = cbind(mydat,myres)
I think I need to clarify a little further on my original question.
I have the following two rows of data:
mydat<-data.frame(d1=c(3,5),d2=c(6,10),p1=c(.55,.05),p2=c(.85,.35))
>mydat
d1 d2 p1 p2
1 3 6 0.55 0.85
2 5 10 0.05 0.35
I need to optimize the following function using optim for each row in mydat
fr<-function(x) {
u<-x[1]
v<-x[2]
sqrt(sum((plnorm(c(d1,d2,u,v)-c(p1,p2))^2))
}
x0<-c(1,1) # starting values for two unknown parameters
y<-optim(x0,fr)
In my defined function fr, (d1 d2 p1 p2) are known values which I need
to read in from my dataframe and u & v are the TWO unknown parameters.
I want to solve this equation for each row of my dataframe.
I can get this to work when I manually plug in the known values (d1 d2
p1 p2). However, I would like to apply this to each row in my dataframe
where the known values are automatically passed to my function which
then is sent to optim which solves for the two unknown parameters for
each row in the dataframe.
thanks again,
mike
--
mmpapenf at wisc.edu