2017-05-04 70 views
0

我試圖創建整潔的數據,我試圖從外地名稱GLM解析直言係數

#Example: 

data(mtcars) 
library(broom) 

#Adding some new character variables 
mtcars1 <- mtcars 
mtcars1$has_leter_yn <- ifelse(grepl("[[:digit:]]" 
           , rownames(mtcars))==TRUE, "1 Y", "2 N") 

mtcars1$first_letter <- substr(rownames(mtcars), 1,1) 

mtcars1$cyl_yn <- ifelse(mtcars$cyl > 5, "Y", "N") 

mtcars1$am_yn <- ifelse(mtcars$am > 0.5, "N", "Y") 

mtcars1$hp_yn <- ifelse(mtcars$hp > 200, "POWER", "WEAK") 

#model 
mod <- glm(mpg ~ wt + first_letter + has_leter_yn + cyl_yn +am_yn + hp_yn 
     , data = mtcars1) 

#broom tidy function 
tidy(mod) 

      term estimate std.error statistic  p.value 
1  (Intercept) 25.46529192 5.155178 4.93974994 0.0001243241 
2    wt -2.38861746 1.338905 -1.78400876 0.0922815327 
3 first_letterC 4.63900549 3.751079 1.23671244 0.2330073046 
4 first_letterD 0.95497914 3.332624 0.28655476 0.7779162451 
5 first_letterF 3.78125890 3.337474 1.13297017 0.2729534747 
6 first_letterH 4.74971469 3.163074 1.50161363 0.1515430178 
7 first_letterL 4.21825272 3.570943 1.18127128 0.2537575961 
8 first_letterM 2.81979616 3.149218 0.89539568 0.3830789592 
9 first_letterP 3.44802708 3.445036 1.00086826 0.3309248121 
10 first_letterT 4.24503396 3.581256 1.18534795 0.2521854417 
11 first_letterV 0.90257581 3.474959 0.25973711 0.7981860095 
12 has_leter_yn2 N 0.06314099 1.394756 0.04527028 0.9644194087 
13   cyl_ynY -4.51802483 1.637415 -2.75924279 0.0134056327 
14   am_ynY -1.33513554 1.827695 -0.73050238 0.4750310328 
15  hp_ynWEAK 3.72962845 2.042696 1.82583649 0.0854925603 

分離特許權價值有沒有辦法來first_letter和C分開?

我想使用估計,術語,&字符在數據框中以供將來使用。任何幫助,將不勝感激!

+0

你是什麼意思?只從係數估計名稱的first_letterC獲得「C」? –

+0

我想要兩列。一個用first_letter和一個用C(每個術語等等)我不確定用這個詞來形容它。 –

+0

你的意思是在迴歸的輸出中有兩列嗎?你能展示最終的輸出應該是什麼樣子? –

回答

1

任何這樣的事情?

xy <- tidy(mod) 

data.frame(letter = gsub(pattern = "^(*.|first_letter)([A-Z])", replacement = "\\2", x = xy$term), 
      prepend = gsub(pattern = "^(*.|first_letter)([A-Z])", replacement = "\\1", x = xy$term), 
      oldterm = xy$term) 

      letter   prepend   oldterm 
1  Intercept)  (ntercept)  (Intercept) 
2    wt    wt    wt 
3    C first_letter first_letterC 
4    D first_letter first_letterD 
5    F first_letter first_letterF 
6    H first_letter first_letterH 
7    L first_letter first_letterL 
8    M first_letter first_letterM 
9    P first_letter first_letterP 
10    T first_letter first_letterT 
11    V first_letter first_letterV 
12 has_leter_yn2 N has_leter_yn2 N has_leter_yn2 N 
13   cyl_ynY   cyl_ynY   cyl_ynY 
14   am_ynY   am_ynY   am_ynY 
15  hp_ynWEAK  hp_ynWEAK  hp_ynWEAK 
+0

真的很接近!我試圖使用這個爲其他變量,如hp_yn或has_leter_yn等這是一個玩具的例子 –

+0

@RyanJohn所以它應該適用於所有變量 - 從變量名稱分隔最後一個大寫字母(級別)? –

+0

是否有一種方法來區分屬於類別的部分:即catagorical_var:01:level,02:level,03:level? –