How do I interpret error: "Error in intI(j, n = x@Dim[2], dn[[2]], give.dn = FALSE) : invalid character indexing" in R?

Viewed 672

I am trying to run this small script in R:

minimumFrequency <- 10

datadtm <- DocumentTermMatrix(datacorpusclean, control=list(bounds = list(global=c(1, Inf
)), weighting = weightBin))

# convert dtm into sparse matrix
datasdtm <- Matrix::sparseMatrix(i = datadtm$i, j = datadtm$j,
                                   x = datadtm$v,
                                   dims = c(datadtm$nrow, datadtm$ncol),
                                   dimnames = dimnames(datadtm))
# calculate co-occurrence counts
coocurrences <- t(datasdtm) %*% datasdtm
# convert into matrix
collocates <- as.matrix(coocurrences)

source("https://slcladal.github.io/rscripts/calculateCoocStatistics.R")

coocTerm <- "selection"

# calculate co-occurence statistics
coocs <- calculateCoocStatistics(coocTerm, datasdtm, measure="LOGLIK")

But in the last row I am getting this error:

Error in intI(j, n = x@Dim[2], dn[[2]], give.dn = FALSE) : invalid character indexing.

I am not an expert in R, could anyone explain me why this happen? What does it exactly mean?

1 Answers

This means that you are trying to extract somehow a column that doesn't exist. Here is a way to reproduce this problem:

library(Matrix)

dd <- data.frame(a = gl(3,4), b = gl(4,1,12))# balanced 2-way
options("contrasts") # the default:  "contr.treatment"
x <- sparse.model.matrix(~ a + b, dd)

x[,"a2"] # works
# 1  2  3  4  5  6  7  8  9 10 11 12 
# 0  0  0  0  1  1  1  1  0  0  0  0 

x[,"fails"] # fails
#Error in intI(j, n = x@Dim[2], dn[[2]], give.dn = FALSE) : 
#  invalid character indexing
Related