I have one data.frame with three columns, Name_of_brand,Price and Quantity. I want to calculate coefficient of linear regression with (lm) function.
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 e.g Brand 1, Brand 2 etc.
Brand 1 Table
Name_of_brand Price Quantitity
1. Brand 1 80 100 2. Brand 1 85 95
Brand 2 Table
Name_of_brand Price Quantitity
3. Brand 2 90 80
4. Brand 2 90 100
5. Brand 2 100 100
Brand 3 etc...
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.
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
:coefficients <- plyr::dlply(model, coef)