# NOT RUN {
## Example 1: creating transactions form a list
a_list <- list(
c("a","b","c"),
c("a","b"),
c("a","b","d"),
c("c","e"),
c("a","b","d","e")
)
## Set transaction names
names(a_list) <- paste("Tr",c(1:5), sep = "")
a_list
## Use the constructor to create transactions
## Note: S4 coercion does the same trans1 <- as(a_list, "transactions")
trans1 <- transactions(a_list)
trans1
## Analyze the transactions
summary(trans1)
image(trans1)
## Example 2: creating transactions from a matrix
a_matrix <- matrix(c(
1,1,1,0,0,
1,1,0,0,0,
1,1,0,1,0,
0,0,1,0,1,
1,1,0,1,1
), ncol = 5)
## Set item names (columns) and transaction labels (rows)
colnames(a_matrix) <- c("a","b","c","d","e")
rownames(a_matrix) <- paste("Tr",c(1:5), sep = "")
a_matrix
## Create transactions
trans2 <- transactions(a_matrix)
trans2
inspect(trans2)
## Example 3: creating transactions from data.frame
a_df <- data.frame(
age = as.factor(c(6, 8, NA, 9, 16)),
grade = as.factor(c("A", "C", "F", NA, "C")),
pass = c(TRUE, TRUE, FALSE, TRUE, TRUE))
## Note: factors are translated differently to logicals and NAs are ignored
a_df
## Create transactions
trans3 <- transactions(a_df)
inspect(trans3)
## Note that coercing the transactions back to a data.frame does not recreate the
## original data.frame.
as(trans3, "data.frame")
## Example 4: creating transactions from a data.frame with
## transaction IDs and items (by converting it into a list of transactions first)
a_df3 <- data.frame(
TID = c(1,1,2,2,2,3),
item=c("a","b","a","b","c", "b")
)
a_df3
trans4 <- transactions(split(a_df3[,"item"], a_df3[,"TID"]))
trans4
inspect(trans4)
## Note: This is very slow for large datasets. It is much faster to
## read transactions using read.transactions() with format = "single".
## This can be done using an anonymous file.
write.table(a_df3, file = tmp <- file(), row.names = FALSE)
trans4 <- read.transactions(tmp, format = "single",
header = TRUE, cols = c("TID", "item"))
close(tmp)
inspect(trans4)
## Example 5: create transactions from a dataset with numeric variables
## using discretization.
data(iris)
irisDisc <- discretizeDF(iris)
head(irisDisc)
trans5 <- transactions(irisDisc)
trans5
inspect(head(trans5))
## Note, creating transactions without discretizing numeric variables will apply the
## default discretization and also create a warning.
## Example 6: create transactions manually (with the same item coding as in trans5)
trans6 <- transactions(
list(
c("Sepal.Length=[4.3,5.4)", "Species=setosa"),
c("Sepal.Length=[4.3,5.4)", "Species=setosa")
), itemLabels = trans5)
trans6
inspect(trans6)
# }
Run the code above in your browser using DataLab