Skip to content

No is.null() for empty dfmSparse object computed by dfm() #811

Description

@contefranz

I found that when I compute a document-feature-matrix using dfm() and a custom dictionary, if no words are matched, then dfm() returns a NULL. The problem arises when I check this using the standard is.null() function which returns a FALSE. In the following you will find the minimal.

# defining a silly dictionary
my_dictionary = dictionary( list( a = c( "asd", "dsa" ),
                                  b = c( "foo", "jup" ) ) )

# writing a little piece of text
raw_text = c( "Wow I can't believe it's not raining!", 
              "Today is a beautiful day. The sky is blue and there are burritos" )

# building the related corpus
my_corpus = corpus( raw_text )
summary( my_corpus )

# building the related DFM base on my silly dictionary
my_dfm = dfm( my_corpus, dictionary = my_dictionary )

# now is.null() returns a FALSE when clearly is not
is.null( my_dfm )

The temporarily workaround I found is to convert my_dfm object to either a matrix or a data.table and check the dimensions as follows.

# in the case of a matrix, we will have the number of columns set to 
# zero while the number of rows correspond to the number of texts detected by corpus().
my_dfm_mat = as.matrix( my_dfm )
dim( my_dfm_mat )

# in the case of a data.table both rows and columns are zero
my_dfm_dt = as.data.table( my_dfm )
dim( my_dfm_dt )

So I guess that to execute a code chunk if and only if the document-feature-matrix is full, one can run something like the following:

# 1. matrix case: 
if ( ncol( my_df_mat ) > 0L ) {
  run your code ...
}

# 2. data.table case
if ( all( dim( my_dfm_dt ) != c( 0L, 0L ) ) ) {
  run your code ...
}

At least this worked for me, but it would be nice to have a direct control to check if dfm() computes an empty matrix.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions