2017-10-14 18 views
2

私は今ここで少しずつ検索してみましたが、私の問題の解決策は実際には見つかりませんでした。フィットしたモデルの方程式に簡単にアクセスして元のデータと一緒に表示するのが簡単です。ここでフィットしてx値の高い密度でRにフィットした元のデータをプロットする

は、これまで働いたコードである:

#the dataframe: 
library(ggplot2) 
df<-data.frame(x=c(0,3,5,7,9,14),y=c(1.7,25.4,185.5,303.9,255.9,0.0)) 

#fitting a third degree polinomial model 
fit1<- lm(y~poly(x, 3, raw=TRUE),data = df) 

#plotting fitted and original values 
ggplot(df, aes(x, y))+ 
    geom_point()+ 
    geom_line(aes(x, y=predict(fit1)), col=2) 

以下プロット結果[赤=値、オリジナル=黒データ予測]次に

red = predicted values, black = original data

を、私はしようとしました後でラインの下の面積を計算したいので、元のデータポイントと比較してモデルが実際にどのように見えるかをよりよく把握してください。 Iは、式

x1<-seq(0:14) 
eq<- 20.35*x1+6.64*x1^2-0.58*x1^3-10.84 

で近似係数の

coef(fit1) 

とタイピングを呼び出すことによってFIT1から係数を抽出することによって試み

はF(X「を抽出」する任意の簡単な方法があります)= x + x^2 + c等は元の値と一緒に高密度(0から14までの無限のx値)で表示しますか?たぶんgeom_line()またはstat_function()を使用していますか?

アドバイスありがとうございます!

+0

初心者だけが説明したこれははっきりとところで、関連するドキュメント( 'predict()')は少し隠されていますが、 '?predict.lm'で見つけることができます。 – AkselA

答えて

1

キーを使用すると、同じ範囲の密度の高いデータを生成するが、モデルを作るために使用されるデータに予測することはできません。ここで

x <- seq(from = min(df$x), to = max(df$x), by = 0.1) 

は完全なコードです:

library(ggplot2) 
df <- data.frame(x = c(0, 3, 5, 7, 9, 14), y = c(1.7, 25.4, 185.5, 303.9, 255.9, 0.0)) 
fit1 <- lm(y ~ poly(x, 3, raw = TRUE), data = df) 

は、密なデータを生成します。

predf <- data.frame(x = seq(from = min(df$x), to = max(df$x), by = 0.1)) 

が密集したデータにYを予測:

predf$y <- predict(fit1, predf) 

プロット:機能を抽出し、AUCを計算するHow to calculate the area under each end of a sine curve をし、ここでの例にそれを適応:興味のある方のために

ggplot(df, aes(x, y))+ 
    geom_point()+ 
    geom_line(data= predf, aes(x, y ), col=2) 

enter image description here

0

、私はここにいくつかの非常に良いコードが見つかりました:

#get the function from the model 
poly3fnct <- function(x){ 
    (fnct <- fit1$coeff[1]+ 
    fit1$coeff[2]* x + 
    fit1$coeff[3]* x^2 + 
    fit1$coeff[4]* x^3) + 
    return(fnct) 
} 

#function to find the roots 
manyroots <- function(f,inter){ 
    roots <- array(NA, inter) 
    for(i in 1:(length(inter)-1)){ 
    roots[i] <- tryCatch({ 
     return_value <- uniroot(f,c(inter[i],inter[i+1]))$root 
    }, error = function(err) { 
     return_value <- -1 
    }) 
    } 
    retroots <- roots[-which(roots==-1)] 
    return(retroots) 
} 
#find the roots or x values for y = 0 
roots <- manyroots(poly3fnct,seq(0,14)) 
roots 

#integrate function 
integrate(poly3fnct, roots[1],roots[2]) 
関連する問題