2017-07-29 60 views
-1

我試圖從(嵌套的)數據框(條件)繪製迴歸係數,爲此我爲每個條件中的嵌套數據運行四個迴歸模型(帶有多個預測變量)。繪製每個模型每個條件的R平方值(參見示例),但現在我想首先根據條件繪製x1的迴歸係數(b爲x1,按降序排列),然後對x2繪製相同的(或甚至由預測者號碼),有人可以幫助我與代碼?如何根據條件繪製(嵌套)迴歸模型的迴歸係數(或模型參數的其他估計值)?

繪製的R

示例 - 多個型號平方值:

# creating data example 

library(modelr) 
library(tidyverse) 
set.seed(123) 
data <- tibble(
condition = replicate(40, paste(sample(c("A", "B", "C", "D"), 1, replace=TRUE))), 
x1 = rnorm(n = 40, mean = 10, sd = 2), 
x2 = rnorm(n = 40, mean = 5, sd = 1.5), 
y = x1*rnorm(n = 40, mean = 2, sd = 1) + x2*rnorm(n = 40, mean = 3, sd = 2)) 

by_condition <- data %>% 
    group_by(condition) %>% 
    nest() 

# looking at data from first condition 
by_condition$data[[1]] 

# regression model function 
reg.model <- function(df) { 
    lm(y ~ x1 + x2, 
    data = df) 
} 

# creating column with models per condition 
by_condition <- by_condition %>% 
    mutate(model = map(data, reg.model)) 

# looking at reg. model for first group 
by_condition$model[[1]] 
summary(by_condition$model[[1]]) 

# graphing R-squared (ascending) per model by condition 

glance <- by_condition %>% 
    mutate(glance = map(model, broom::glance)) %>% 
    unnest(glance) 

glance %>% 
    ggplot(aes(x = reorder(condition, desc(r.squared)), y = r.squared)) + 
    geom_point() + 
    coord_flip() + 
    xlab("Condition") + 
    ggtitle("R Square of reg. model per Condition") 

所以這個例子的作品,但我不知道如何seperately提取係數,並通過類似的圖表繪製條件的降序排列。由於

回答

0

我找到了答案,繪製不同的條件範圍內(嵌套)迴歸模型的係數(整理踢屁股):

by_condition %>% 
    mutate(regressions = map(model, broom::tidy)) %>% 
    unnest(regressions) 

by_condition 

regression_output <- by_condition %>% 
    mutate(regressions = map(model, broom::tidy)) 

regression_coefficients <- regression_output %>% 
    unnest(regressions) 

regression_coefficients %>% 
    ggplot(aes(x = term, y = estimate)) + 
    geom_point() + 
    coord_flip() + 
    facet_wrap(~ condition) + 
    xlab("predictor") + 
    ggtitle("Coefficients of reg. model per Condition")