library(Matrix)
# Creating a table of buyers
buyer <- data.frame(Buyers = c("Robert", "Stewart", "Kristen",
"Joe", "Kriti", "Rafel"))
buyer
# Creating a table of cars
car <- data.frame(Cars = c("Maruti", "Sedan", "SUV", "Baleno",
"Hyundai", "BMW","Audi"))
car
# Creating a table of orders: (Buyers, cars, units)
# triplets
order <- data.frame(Buyers = c("Robert", "Robert", "Stewart",
"Stewart", "Kristen", "Kristen",
"Joe", "Kriti", "Joe"),
Cars = c("Maruti", "Maruti", "BMW", "BMW",
"Audi", "Audi", "Maruti", "Audi",
"Sedan"))
# Insert the RowIndex column, identifying
# the row index to assign each buyer
order$RowIndex <- match(order$Buyers, buyer$Buyers)
# Insert the ColIndex column, identifying
# the column index to assign each car
order$ColIndex <- match(order$Cars, car$Cars)
# Now inspect
order
# Creating a basic sparse matrix where element
# (i,j) is true if buyer i bought
# car j and false, otherwise
msparse1 <- sparseMatrix( i = order$RowIndex, j = order$ColIndex)
msparse1
# Creating another sparse matrix to make sure
# every buyer and every car appears in our matrix
# by setting the dimensions explicitly
msparse2 <- sparseMatrix( i = order$RowIndex, j = order$ColIndex,
dims = c(nrow(buyer), nrow(car)),
dimnames = list(buyer$Buyers, car$Cars))
msparse2
# Creating another sparse matrix indicating number
# of times buyer i bought car j
msparse3 <- sparseMatrix( i = order$RowIndex, j = order$ColIndex, x = 1L,
dims = c(nrow(buyer), nrow(car)),
dimnames = list(buyer$Buyers, car$Cars))
msparse3