简体   繁体   English

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

[英]Can I create a sparse matrix in R from SQL Server

In the past I have run Apriori in R using the "arules" package. 过去,我使用“ arules”软件包在R中运行Apriori。 In the past I have done this using flat files in R studio with the following code: 过去,我是使用R Studio中的平面文件通过以下代码完成此操作的:

# 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)

For the first time I am working with data in SQL Server and using R Tools in visual studio. 我是第一次使用SQL Server中的数据并在Visual Studio中使用R Tools。

Here is the script I'm running: 这是我正在运行的脚本:

#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);

Is there a method I can use to then convert this to a sparse matrix like I do with the static file? 有没有一种方法可以像将静态文件一样将其转换为稀疏矩阵?

I could write a T-SQL query to pivot the data and create a sparse matrix that way but I'd like to know if I can do it efficiently in R. 我可以编写一个T-SQL查询来透视数据并以这种方式创建一个稀疏矩阵,但是我想知道是否可以在R中高效地进行处理。

Here is a sample of data Im working with: 这是Im处理的数据样本:

CREATE TABLE #SomeData
(
SaleId INT
, Item1 NVARCHAR (500)
, Item2 NVARCHAR (500)
, Item3 NVARCHAR (500)
, Item4 NVARCHAR (500)
, Item5 NVARCHAR (500)
, Item6 NVARCHAR (500)
, Item7 NVARCHAR (500)
, Item8 NVARCHAR (500)
, Item9 NVARCHAR (500)
, Item10 NVARCHAR (500)
, Item11 NVARCHAR (500)
, Item12 NVARCHAR (500)
, Item13 NVARCHAR (500)
, Item14 NVARCHAR (500)
, Item15 NVARCHAR (500)
, Item16 NVARCHAR (500)
, Item17 NVARCHAR (500)
, Item18 NVARCHAR (500)
, Item19 NVARCHAR (500)
, Item20 NVARCHAR (500)
)

INSERT INTO #SomeData
VALUES
    (1, N'shrimp', N'almonds', N'avocado', N'vegetables mix', N'green grapes', N'whole weat flour', N'yams', N'cottage cheese', N'energy drink', N'tomato juice', N'low fat yogurt', N'green tea', N'honey', N'salad', N'mineral water'
   , N'salmon', N'antioxydant juice', N'frozen smoothie', N'spinach', N'olive oil')
  , (2, N'burgers', N'meatballs', N'eggs', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
  , (3, N'chutney', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
  , (4, N'turkey', N'avocado', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
  , (5, N'mineral water', N'milk', N'energy bar', N'whole wheat rice', N'green tea', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)

SELECT * FROM #SomeData

Thanks 谢谢

If I've understood well you have a table similar to this: 如果我了解得很好,您将有一个类似于以下的表格:

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

Unluckily I've worked with R (RStudio) and MSSMS+R (embed R code in SQL) , but not with Visual Studio, so I can give you some pseudo-code as reasoning and hint: 不幸的是,我使用过R(RStudio)和MSSMS + R(在SQL中嵌入R代码) ,但没有使用Visual Studio,因此我可以给您一些伪代码作为推理和提示:

First of all, you have to reduce your table to a two-column table, with the ID and the products: if we have a fake table like this: 首先,您必须使用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

To be more precise, you'd remove the rows with NA , but the idea is the same. 更准确地说,您将使用NA删除行,但是想法是一样的。
Now you can create your transaction matrix: 现在,您可以创建交易矩阵:

  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)

Last, you can apply your apriori algorithm: 最后,您可以应用先验算法:

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   

As further information, take a look also to the package sqldf and RODBC , to manage data.frame with query in R environment and to connect R via ODBC. 作为进一步的信息,还请查看软件包sqldfRODBC ,以在R环境中通过查询管理data.frame并通过ODBC连接R。

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

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