我试图从模型中自动化图形(拟合模型输入变量,拟合模型输出变量),并希望从nlme()结果中隔离输入和输出变量名称。
我设法看起来像一个非常脏的解决方案。你有更优雅的分享吗?
谢谢!
这是一个例子:
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))
我想做数据$ output&lt; - data $ leg但是自动化:
output_var <- eval(parse(text=paste(m1$call$data, as.character(m1$call$model)[2], sep="$")))
df$output <- output_var
我想做数据$ input&lt; - data $ foot但是自动化:
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)
这样我就可以在我的ggplot中使用泛型变量:
ggplot(df)+
geom_point(aes(x=input, y=output, colour = region))+
geom_line(aes(x=input, y=fit_m1))
答案 0 :(得分:1)
以下是使用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))