[R] Plot fitted vs observed values

Duncan Murdoch
2009-11-28T15:13:52Z

On 28/11/2009 9:25 AM, oscar linares wrote:
> Dear Wiza[R]ds,
>
> # I have the following experimentally observed data:
>
> csdata <- data.frame(
> time=c(0,1,3,9,20),
> conc=c(638.697,395.69,199.00,141.58,112.16)
> )
>
> # weighting resp means response
> wt.MM<- function(resp, time,A1,a1,A2,a2)
> {
>     pred <- A1*exp(-a1*time)+A2*exp(-a2*time)
>     (resp - pred) / sqrt(pred)
> }
>
> # Fit using nls
> cs.wt <- nls( ~ wt.MM(conc, time,A1,a1,A2,a2), data=csdata,
>               start=list(A1=700,a1=1,A2=100,a2=0.1),
>               trace = TRUE)
>
> x<-csdata$time
> y<-csdata$conc
>
> # I want to plot the observed vs. fitted values in both linear(y) and
log(y)
> plots (i.e., linear and semi-log plots)
> # Help appreciated...I spent over 2 hours searching archives.

Because your wt.MM doesn't return the pred values, you'll need to write
a function that does.  For example,

predictions <- function(fit, time) {
    params <- summary(fit)$coefficients[, 1]
    A1 <- params["A1"]
    a1 <- params["a1"]
    A2 <- params["A2"]
    a2 <- params["a2"]
    A1*exp(-a1*time)+A2*exp(-a2*time)
}

times <- seq(0,20, len=100)
par(mfrow=c(2,1))
plot(conc ~ time, data=csdata)
lines(times, predictions(cs.wt, times))
plot(conc ~ time, data=csdata, log="y")
lines(times, predictions(cs.wt, times))


Duncan Murdoch