R中无需read.transactions函数的Apriori关联规则分析问题
read.transactions() (In-Memory Data Frame) Got it, let's tackle this problem directly—since you can't use read.transactions() (it relies on file inputs), we can convert your existing data frame into the transactions format that arules needs entirely in memory. Here's how to do it step by step with your sample data:
Step 1: Clean Up Your Sample Data
First, let's properly define your test data frame (I'll add explicit column names and ensure strings aren't treated as factors):
test <- data.frame( transaction_id = c(1, 2, 3, 4, 5), items = c("1, 2, 3", "2, 4", "1, 5, 2", "4, 1", "2, 3, 4, 5"), stringsAsFactors = FALSE )
Step 2: Convert the Comma-Separated Column to a Transaction List
We'll split the comma-separated strings into a list of character vectors (each vector represents one transaction's items). Note that we handle the spaces after commas in your data:
# Split each item string into a vector of individual items transaction_list <- strsplit(test$items, ", ") # Optional: Name each transaction with its ID for clarity names(transaction_list) <- test$transaction_id
If your item strings might have inconsistent spacing (e.g., sometimes no space after commas), use this more robust version to strip all whitespace first:
transaction_list <- strsplit(gsub("\\s", "", test$items), ",")
Step 3: Convert the List to a transactions Object
The arules package lets you convert a list directly to a transactions object using as():
# Load the arules package (if not already loaded) library(arules) # Convert the list to the required transactions format transactions <- as(transaction_list, "transactions")
Step 4: Verify & Run Apriori
Check that your transactions are correctly formatted:
inspect(transactions)
You should see output like this:
items transactionID [1] {1,2,3} 1 [2] {2,4} 2 [3] {1,2,5} 3 [4] {1,4} 4 [5] {2,3,4,5} 5
Now you can run the Apriori algorithm just like you would with a file-based transactions object:
# Adjust support/confidence parameters as needed rules <- apriori(transactions, parameter = list(supp = 0.2, conf = 0.5)) # Inspect the generated rules inspect(rules)
This approach keeps everything in memory, so it works across any environment where you have your data frame loaded—no file I/O required.
内容的提问来源于stack exchange,提问作者Cezary

