2016-10-02 215 views
-1

我有代碼將線性模型擬合到R中的數據。我的自變量是AGE,我的因變量是Costs。我感興趣的是,成本在一般情況下會隨着年限增加。然而,對於某些部分我的攔截是10,而對於其他部分,我的攔截是1000,因此貨幣單位的增加沒有幫助,因爲每年1個單位的斜率對於10的截距和1個貨幣單位的斜率可能很大每年是可以忽略的。任何人都可以幫助解決這個問題,在R中對斜率進行標準化處理,然後用lm進行比較後再進行比較?具有不同截距的線性模型的斜率:如何標準化/標準化斜率以進行比較?

data.ex <- data.frame(Age = c(c(1:10), c(1:10)), 
        Costs = c(11,12,13,14,15,12,17,18,19,20, 1001,1002,1003,1004,999,1006,1007,1008,1009,1010), 
        Type = c(rep("A", 10), rep("B", 10))) 
pt <- ggplot(data = data.ex, aes(x=Age, y = Costs))+ 
geom_smooth(method="lm")+ 
facet_wrap(facets = "Type", nrow = 2) 
plot(pt) 
print(with(data.ex[data.ex$Type == "A", ], lm(Costs ~ Age))) 
print(with(data.ex[data.ex$Type == "B", ], lm(Costs ~ Age))) 
+1

將'scales =「free_y」'參數添加到'facet_wrap' –

回答

1

正如指出的他人,在facet_wrap設置scales = 'free'將兩條線中的情節更加明顯。

對於你的另一個問題,你的措辭有點不清楚,但聽起來像你在說:「如果基線成本從10美元開始,那麼每年增加1美元是相當可觀的,而基線成本爲1000美元,每年1美元並不重要,我如何顯示這種差異?「

一種方法是標準化每個小組針對其攔截:

library(dplyr) 

# calculate intercepts for each group and extract them: 
intercept.ex <- group_by(data.ex, Type) %>% 
    do(data.frame(intercept = coef(lm(Costs ~ Age, data = .))[1])) 

# normalize the values in each group against their intercepts 
data.ex <- merge(data.ex, intercept.ex) %>% 
    mutate(Costs = Costs/intercept) 

# Age slope = 0.1002 
print(with(data.ex[data.ex$Type == "A", ], lm(Costs ~ Age))) 

# Age slope = 0.001037 
print(with(data.ex[data.ex$Type == "B", ], lm(Costs ~ Age))) 

我應該指出的是,這兩個斜坡仍然統計顯著,因爲年齡和成本之間的關係是很清楚的。但是相對效應大小在它們之間是非常不同的。

+0

我從代碼中學到了很多東西,其中也包括我最喜歡的軟件包之一dplyr。謝謝!! 你知道我的問題爲什麼downvoted嗎?我有點困惑,我做錯了什麼? – rashid

+0

噢,你可以概述一下使用「do」調用的優點嗎?謝謝:) – rashid

+1

你的問題的措辭有點不清楚,這就是爲什麼你得到一個投票。至於'do',這個函數是爲了和'group_by'一起工作,對每個由group_by'創建的組應用一個函數或一組命令。 – jdobres

1

你可以嘗試使用y軸的不同規模......但其實我真的不明白你的問題。

Age = c(1:10) 
Costs = c(11,12,13,14,15,12,17,18,19,20) 
plot(Age, Costs, type="l", col="blue", lwd=2) 

Costs = c(1001,1002,1003,1004,999,1006,1007,1008,1009,1010) 
plot(Age, Costs, type="l", col="blue", lwd=2) 
相關問題