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.
I found that when I compute a document-feature-matrix using
dfm()and a custom dictionary, if no words are matched, thendfm()returns aNULL. The problem arises when I check this using the standardis.null()function which returns aFALSE. In the following you will find the minimal.The temporarily workaround I found is to convert
my_dfmobject to either a matrix or a data.table and check the dimensions as follows.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:
At least this worked for me, but it would be nice to have a direct control to check if
dfm()computes an empty matrix.