簡體   English   中英

循環創建回歸模型

[英]Loop to create Regression Models

我有一個由x個區域和通道的唯一組合組成的數據框。 我需要使用某種循環為每個x組合創建一個獨特的回歸模型。

region  channel         date         trials    spend    
EMEA    display       2015-01-01       62     17875.27   
APAC    banner        2015-01-01       65     18140.93

有影響的東西

i=1
j=1
for r in region{
   for ch in channel{
       df1 = df[df$region == r & df$channel == ch, ]
       model[[i,j]] = lm(trials ~ spend, data = df1)
                      j = j+1}
                i = i+1 }

如果有人也知道一種存儲唯一標識符(例如region + channel)的方法來幫助識別回歸模型,那也將非常有幫助。

一個plyr解決方案:

set.seed(1)
d <- data.frame(region = letters[1:2],
                channel = LETTERS[3:6],
                trials = runif(20),
                spend = runif(20))

列出結果(即按區域和通道划分d ,使用指定的公式在每個塊上運行lm ,將結果作為列表返回)

library(plyr)
res <- dlply(d,c("region","channel"), lm,
             formula=trials~spend)

提取系數作為數據框:

ldply(res,coef)
##   region channel (Intercept)      spend
## 1      a       C   0.3359747  0.2444105
## 2      a       E   0.7767959 -0.3745419
## 3      b       D   0.7409942 -0.8084751
## 4      b       F   1.0797439 -1.0872158

請注意,結果中有您想要的區域/通道標識符...

使用split的數據轉換成2名的組合作為列表中,然后運行lm環內- lapply用於數據的每個子集,參見本實施例中:

# dummy data
set.seed(1)
d <- data.frame(region = letters[1:2],
                channel = LETTERS[3:6],
                trials = runif(20),
                spend = runif(20))

# split by 2 column combo
dSplit <- split(d, paste(d$region, d$channel, sep = "_"))

# run lm for each subset
res <- lapply(dSplit, lm, formula = trials ~ spend)

# check names
names(res)
# [1] "a_C" "a_E" "b_D" "b_F"

# lm result for selected combo "a_C"
res$a_C
# Call:
#   lm(formula = trials ~ spend, data = i)
# 
# Coefficients:
#   (Intercept)        spend  
# 0.3360       0.2444  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM