我可以从SQL Server在R中创建稀疏矩阵吗

时间:2018-08-30 05:45:03

标签: r sql-server microsoft-r

过去,我使用“ arules”软件包在R中运行Apriori。过去,我是使用R Studio中的平面文件通过以下代码完成此操作的:

using (var service = new dB.Business.Service.BaseBusinessService<memo>())
   {
      List<memo> result = service.Repository.GetQuery().Where(p => p.ID == ID && p.eventTriggers.Contains('1')).ToList();
   }

我第一次在SQL Server中处理数据并在visual studio中使用R工具。

这是我正在运行的脚本:

# install.packages('arules');
library(arules);

# the following is how I bring in flat files:
ds = read.csv('somedata.csv', header = FALSE)

# and here is how I import this data but as a sparse matrix:
dsSparse = read.transactions('somedata.csv', sep = ',', rm.duplicates = TRUE)

是否有一种方法可以像将静态文件一样将其转换为稀疏矩阵?

我可以编写一个T-SQL查询以透视数据并以这种方式创建稀疏矩阵,但我想知道我是否可以在R中高效地做到这一点。

以下是我正在处理的数据示例:

#Connection to SQL Server.
connStr = paste("Driver=SQL Server; Server=", "MyServer", ";Database=", "MyDatabase", ";Trusted_Connection=true;", sep = "");
#Get data from SQL Query
SQL_ds = RxSqlServerData(sqlQuery = "SELECT * FROM dbo.SomeData", connectionString = connStr, returnDataFrame = TRUE);
#Run the query and store the data into the table
ds = rxImport(SQL_ds);

谢谢

1 个答案:

答案 0 :(得分:1)

如果我对您的表很了解,您将有一个类似于以下的表格:

id item1 item2 ... itemn
1  a     s         n1
2  a     s         n2
3  c     d         n4
4  c     e         n3
...
m  m1    m2        mn

不幸的是,我使用过R(RStudio)和MSSMS+R (embed R code in SQL),但没有使用Visual Studio,因此我可以给您一些伪代码作为推理和提示:

首先,您必须将表简化为带有ID和产品的两列表:如果我们有这样的假表:

library(arules)
library(tidyverse)
fake <- data.frame(id = c(1,2,3,4,5),
                   item1 = c('a','a','a',NA,'b'),
                   item2 = c('d','d','d',NA,NA),
                   item3 = c('e','e','c','k','b'))

> fake
  id item item item
1  1    a    d    e
2  2    a    d    e
3  3    a    d    c
4  4 <NA> <NA>    k
5  5    b <NA>    b

colnames(fake) <- c('id','item','item','item')
df <- rbind(fake[,c(1,2)],fake[,c(1,3)],fake[,c(1,4)])

 # here we go
 > df
   id item
1   1    a
2   2    a
3   3    a
4   4 <NA>
5   5    b
6   1    d
7   2    d
8   3    d
9   4 <NA>
10  5 <NA>
11  1    e
12  2    e
13  3    c
14  4    k
15  5    b

更精确地说,您将使用NA删除行,但是想法是相同的。
现在,您可以创建交易矩阵:

  df <- df %>%
  select(id, item) %>%
  distinct() %>%
  mutate(value = 1) %>%
  spread(item, value, fill = 0)
  > df
  id a b d c e k <NA>
1  1 1 0 1 0 1 0    0
2  2 1 0 1 0 1 0    0
3  3 1 0 1 1 0 0    0
4  4 0 0 0 0 0 1    1
5  5 0 1 0 0 0 0    1
  # here is necessary the arules package
  itemMatrix <- as(as.matrix(df[, -1]), "transactions")
  > itemMatrix
  transactions in sparse format with
  5 transactions (rows) and
  7 items (columns)

最后,您可以应用先验算法:

rules <- apriori(itemMatrix, parameter = list(supp = 0.4, conf = 0.8, target = "rules"))
rules_conf <- sort (rules, by="support", decreasing=TRUE)
inspect(rules_conf)

   lhs      rhs support confidence lift     count
[1] {d}   => {a} 0.6     1          1.666667 3    
[2] {a}   => {d} 0.6     1          1.666667 3    
[3] {e}   => {d} 0.4     1          1.666667 2    
[4] {e}   => {a} 0.4     1          1.666667 2    
[5] {d,e} => {a} 0.4     1          1.666667 2    
[6] {a,e} => {d} 0.4     1          1.666667 2   

作为进一步的信息,请查看软件包sqldfRODBC,以在R环境中通过查询管理data.frame并通过ODBC连接R。