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) ______________________________________________ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.