0

I am trying to automatize plots (fitted vs model input variable, fitted vs model output variable) from models and would like to isolate the input and output variable names from the nlme() results.

I managed with something looking like a very dirty solution. Do you have anything more elegant to share?

Thanks!

here is an example:

df <- data.frame(foot = c(18,49.5,36.6,31.55,8.3,17,30.89,13.39,23.04,34.88,35.9,47.8,23.9,31,29.7,25.5,10.8,36,6.3,46.5,9.2,29,5.4,7.5,34.7,16.8,45.5,28,30.50955414,30.2866242,65.9,26.6,12.42038217,81.8,6.8,35.44585987,7,45.8,29,16.7,19.6,46.3,32.9,20.9,40.6,10,21.3,18.6,41.4,6.6), 
             leg = c(94.3588,760.9818,696.9112,336.64,12.43,69.32,438.9675,31.8159,153.6262,473.116,461.66276,897.7088,131.6944,395.909156,633.1044,179.772,41.3292,457.62,9.072,870.74,18.6438,356.64,5.3486,8.802,452.425561,82.618,839.649888,276.73016,560.63,655.83,2287.6992,234.1807,63,3475.649195,14.098,837.35,10.01,1149.87,615.03,124.35,184.33,1418.66,707.25,123.62,687.87,24.9696,192.416,181.5872,954.158,10.1716),
             region=c(rep("a",13), rep("b", 17), rep("c", 20)),
             disease = "healthy")

df$g <- "a" #No random effect wanted

m1 <- nlme(leg~a*foot^b,
       data = df,
       start= c(1,1),
       fixed=a+b~1,
       groups=~g,
       weights=varPower(form=~foot))

I want to do data$output <- data$leg but automatised:

output_var <- eval(parse(text=paste(m1$call$data, as.character(m1$call$model)[2], sep="$")))
df$output <- output_var

I want to do data$input <- data$foot but automatised:

input_var <- eval(parse(text=paste(m1$call$data, gsub('a|b| |\\*|\\/|\\+|\\-|\\^', '', as.character(m1$call$model)[3]), sep="$")))
df$input <- input_var

df$fit_m1 <- fitted.values(m1)

So that I can use generic varaibles in my ggplot:

ggplot(df)+ 
geom_point(aes(x=input, y=output, colour = region))+
geom_line(aes(x=input, y=fit_m1))
David
  • 100
  • 1
  • 8

1 Answers1

1

Here is a solution using broom::augment

library(nlme)
library(ggplot)
library(broom)
# Get the fitted values along with the input and output
augmented <- augment(m1, data=df)
# Change the names of the dataframe so you have our standard input and output
new_names <- names(augmented)
new_names[c(1, 2)] <- c('input', 'output')
names(augmented) <- new_names
# Then you can plot using your standard names
ggplot(augmented, aes(input)) +
  geom_point(aes(y = output, color = region)) +
  geom_line(aes(y = .fitted))

plot

FlorianGD
  • 2,336
  • 1
  • 15
  • 32