简体   繁体   English

为线性回归创建循环

[英]Creating a loop for linear regression

I have one data.frame with three columns, Name_of_brand,Price and Quantity.我有一个包含三列的 data.frame,Name_of_brand、Price 和 Quantity。 I want to calculate coefficient of linear regression with (lm) function.我想用 (lm) 函数计算线性回归的系数。

    Name_of_brand       Price     Quantitity
1.    Brand 1              80         100
2.    Brand 1              85          95
3.    Brand 2              90          80
4.    Brand 2              90         100
5.    Brand 2             100         100
6.    Brand 3             150          80
7.    Brand 4             155          70
8.    Brand 5             165          70
9.    Brand 5             165          60
10.   Brand 6             170          60
11.   Brand 7             180          60
12.   Brand 7             180          60
13.   Brand 7             180          70
14.   Brand 8             170          80
15.   Brand 8             170          60

First I want to convert figures in log, group by Name_of _brand and after that calculate elasiticity for price for each like example below eg Brand 1, Brand 2 etc.首先,我想转换日志中的数字,按 Name_of _brand 分组,然后计算每个类似示例的价格弹性,例如品牌 1、品牌 2 等。

Brand 1 Table品牌1表

Name_of_brand       Price    Quantitity

1. Brand 1 80 100 2. Brand 1 85 95 1. 品牌 1 80 100 2. 品牌 1 85 95

Brand 2 Table品牌2表

    Name_of_brand       Price    Quantitity
3.    Brand 2              90          80
4.    Brand 2              90         100
5.    Brand 2             100         100

Brand 3 etc...品牌3等...

And the end I want to get final_table with two columns, first column with Name_of_brand and Coeff_elasticity.最后我想得到两列的 final_table,第一列是 Name_of_brand 和 Coeff_elasticity。

Final_table Final_table

    Name_of_brand  Coeff_elasticity.
1.    Brand 1            -0,5
2.    Brand 2            -0,6
3.    Brand 3            -0,7
4.    Brand 4            -0,7
5.    Brand 5            -0,5
etc.

Can anyone help me with some code for calculation?谁能帮我一些计算代码?

There is no need to explicitly separate your data into several subsets.无需将您的数据明确地分成几个子集。

model <- plyr::dlply(data, "Name_of_brand", function(df) lm(log(Quantitity) ~ log(Price), data = df))

You may retrieve the coefficients for each level of "Name_of_brand" using coef :您可以使用coef检索“Name_of_brand”每个级别的coef

coefficients <- plyr::dlply(model, coef)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM