I am trying to write a code to do sequence analysis. However, I get the error Seqdist Error: ‘sm’ invalid type or unknown value. I tried it all to find why it happens but I am stuck. I could find out that it works if I have a single variable and single substitution matrix.
Any help would be greatly appreciated
See some simplified example of the code below:
# Libraries
library(TraMineR)
library(cluster)
library(ggplot2)
# Simplified Sample Data
dimension_1_reduced <- data.frame(
contract_inst = c(1, 2, 3, 4, 1, 4, 3, 2, 1, 4, 3, 2, 1, 4, 3, 2, 1, 4, 3, 2), # 20 items, 4 levels
contract_temp = c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2) # 20 items, 2 levels
)
# Reduced Sequence Object
seq_obj_1_reduced <- seqdef(dimension_1_reduced,
states = list(
contract_inst = c("1", "2", "3", "4"),
contract_temp = c("1", "2")
))
# Print the sequence object
print(seq_obj_1_reduced)
# Check structure of the sequence object
str(seq_obj_1_reduced)
# Access attributes
# 1. Sequence data
seq_data <- attr(seq_obj_1_reduced, "data")
print(seq_data)
# 2. Column names
column_names <- colnames(seq_data)
print(column_names)
# 3. State levels
state_levels <- attr(seq_obj_1_reduced, "labels")
print(state_levels)
# Substitution Matrices with State Labels
matrix_inst <- matrix(c(0, 1, 2, 3,
1, 0, 1, 2,
2, 1, 0, 1,
3, 2, 1, 0), nrow = 4,
dimnames = list(c("1", "2", "3", "4"), c("1", "2", "3", "4")))
matrix_temp <- matrix(c(0, 1,
1, 0), nrow = 2,
dimnames = list(c("1", "2"), c("1", "2")))
# List of substitution matrices for reduced dimensions
sm_list_reduced <- list(contract_inst = matrix_inst,
contract_temp = matrix_temp)
# Compute reduced dissimilarity matrix
dissimilarity_reduced <- tryCatch({
seqdist(seq_obj_1_reduced, method = "OM", sm = sm_list_reduced, indel = 1)
}, error = function(e) {
print(e)
NULL
})
# Check for errors
if (!is.null(dissimilarity_reduced)) {
print(dissimilarity_reduced)
} else {
print("Error in calculating the dissimilarity matrix")
}
I tried to print all variables to check that the substitution matrixes matched the corresponding dimension. I tried running a dimension with a single variable, which works. I tried looking into forums or posts to see if someone encountered the same problem. I tried reading the R package TraMineR.