【问题标题】:Linear regression in R with data from Sql serverR中的线性回归与来自Sql server的数据
【发布时间】:2014-01-08 06:56:49
【问题描述】:

我想从 MS Sql Server 导入数据并对 R 中的数据应用线性回归。但我不确定如何操作来自 sql server 的数据以便进行回归。我在sql server中的表是这样的,

Pack    Cubes   Name    Sales
1001    1.2      A      10
1001    1.2      B      12
1002    0.9      A      8
1002    0.9      B      5
1002    0.9      C      12
1003    1.5      A      5
1003    1.5      C      10
1004    0.8      B      8
1004    0.8      C      10
1005    1.3      A      5
1005    1.3      B      8
1005    1.3      C      12

如果我要在 excel 中为回归模型处理数据,它看起来像这样,

Cubes   A   B   C
1.2    10   12  0
0.9    8    5   12
1.5    5    0   10
0.8    0    8   10
1.3    5    8   12

A、B、C 是我的因变量,Cubes 是我的自变量。我的 sql 表中的 Pack 只是一个参考。我与 DSN 的 Sql 连接看起来像这样(完美运行),

library(RODBC)
myconn <- odbcConnect("sqlserver")
data <- sqlQuery(myconn,"select Cubes,Name,Sales from mytable")

我尝试了回归(这是错误的),

summary(data)
reg<-lm(Cubes~Sales,data)
summary(reg)

我如何像在 excel 中那样操作来自 sql server 的数据?

【问题讨论】:

    标签: sql sql-server r excel linear-regression


    【解决方案1】:

    尝试 reshape 或 reshape 包:

    wide <- reshape(data, v.names = "Sales", idvar = "Cubes",
                timevar = "Name", direction = "wide")
    

    【讨论】:

    • +1,虽然要准确获得 OP 要求的内容,但您需要将 NA 替换为 0。
    • 谢谢,重塑工作,我刚刚添加了使 NA 等于 0 的 wide[is.na(wide)]=0。
    【解决方案2】:

    我会使用 reshape2 包中的 dcast。请注意,dcast 导致 NA 不存在 NameSales 的组合。您需要手动将其更改为0

    res = dcast(df, Cubes ~ Name, value.var = 'Sales')
    res[is.na(res)] = 0
    res
      Cubes  A  B  C
    1   0.8  0  8 10
    2   0.9  8  5 12
    3   1.2 10 12  0
    4   1.3  5  8 12
    5   1.5  5  0 10
    

    【讨论】:

      【解决方案3】:

      您可以使用 SQL 以您需要的格式直接从 SQL Server 获取数据,如下所示:

         SELECT Cubes,
          SUM(CASE WHEN Name='A' then Sales else 0 END) A,
          SUM(CASE WHEN Name='B' then Sales else 0 END) B,
          SUM(CASE WHEN Name='C' then Sales else 0 END) C
          FROM mytable
          GROUP BY Cubes
      

      【讨论】:

        猜你喜欢
        • 2014-12-26
        • 2020-11-01
        • 2018-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多