钻石与价格预测

来源:互联网 发布:mac bird进程 编辑:程序博客网 时间:2024/06/10 19:47

将两组数据图在一幅图中显示

plot1 <- qplot(data= diamonds, x= price,                binwidth= 100, fill= I('#FFFF00')) +   ggtitle('Price')plot2 <- qplot(data= diamonds, x= price,   binwidth= 0.01, fill= I('#00FFFF')) +  ggtitle('Price (log10)')+  scale_x_log10()grid.arrange(plot1, plot2, ncol= 2)

效果如图所示:

这里写图片描述

散点图转化:立方根

# 立方根转换函数# 这个函数去所有输入变量的立方根,他还有一个反函数,用于撤销该运算正确显示绘图cuberoot_trans = function()trans_new('cuberoot',                                     transform = function(x), x^1/3,                                    inverse = function(x), x^3)

添加标题

  ggplot(aes(x = carat, y = price, color = cut), data = diamonds) +   geom_point(alpha = 0.5, size = 1, position = 'jitter') +  scale_color_brewer(type = 'div',                     guide = guide_legend(title = 'haha', reverse = T,                                          override.aes = list(alpha = 1, size = 2))) +    scale_x_continuous(trans = cuberoot_trans(), limits = c(0.2, 3),                     breaks = c(0.2, 0.5, 1, 2, 3)) +   scale_y_continuous(trans = log10_trans(), limits = c(350, 15000),                     breaks = c(350, 1000, 5000, 10000, 15000)) +  ggtitle('Price (log10) by Cube-Root of Carat and cut')

效果如图所示:

这里写图片描述

lm函数:构建线型模型

lm函数的用法如图所示:

这里写图片描述

构建方法如下:

# 这里用到了I wrapeer,在这个例子中,他告诉R使用I函数内部的表达式来转换变量然后用于递归# 这样就替代了引导R来解释公式中的这些符号,以此构成递归矩阵设计过程m1 <- lm(I(log(price)) ~ I(carat^(1/3)), data = diamonds)m2 <- update(m1, ~ . + carat)m3 <- update(m2, ~ . + cut)m4 <- update(m3, ~ . + color)m5 <- update(m3, ~ . + clarity)mtable(m1, m2, m3, m4, m5)

为更大的钻石数据集构建线性模型

要求是只取钻石价格小于1万美元的。而且只要GIA认证的钻石

# 首先用log处理一下diamondsbig <- load('D:\\BigDiamonds.Rda')diamondsbig$logprice = log(diamondsbig)    m1 <- lm(logprice ~ I(carat^(1/3)),          data = diamondsbig[diamondsbig$price<10000 &                               diamondsbig$cert == 'GIA',])m2 <- update(m1, ~ . + carat)m3 <- update(m2, ~ . + cut)m4 <- update(m3, ~ . + color)m5 <- update(m3, ~ . + clarity)mtable(m1, m2, m3, m4, m5)

扩展阅读

你卖过钻石吗?:https://www.theatlantic.com/magazine/archive/1982/02/have-you-ever-tried-to-sell-a-diamond/304575/

De Beers 的钻石垄断:https://en.wikipedia.org/wiki/De_Beers#Diamond_monopoly

R 中的线性模型和运算符:http://data.princeton.edu/R/linearModels.html

用 R 分析你的 Facebook 社交网络!:http://blog.revolutionanalytics.com/2013/11/how-to-analyze-you-facebook-friends-network-with-r.html