Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

nlp - Error in tolower(txt) non character argument in R (for textmining)

So as a beginner, I'm trying to do simple text-mining (NLP) using R language.

I preprocessed my data using tm_map function and inspected it and all the punctuations, numbers were removed. I also converted the text document in lower case using tolower() function. It worked great.

But while creating a document matrix, I'm encountering an issue where the error is:

error in tolower(txt): non character argument

What is this error about and how to go ahead with this? Is this something related to UTF8? Any leads would be appreciated.

docs <- tm_map(docs, removePunctuation) 
inspect(docs[1]) 

for(j in seq(docs)) { 
  docs[[j]] <- gsub("
", " ", docs[[j]]) 
} 

docs <- tm_map(docs, removeNumbers) 
docs <- tm_map(docs, content_transformer(tolower)) 
docs <- tm_map(docs, removeWords, stopwords("english")) 
docs <- tm_map(docs, stripWhitespace) 

This all worked just fine and my text document (which is simply an ebook) got converted into lower case, with no white spaces, numbers, etc. just fine and the next step returns the error.

# returns the above error. 
dtm <- DocumentTermMatrix(docs)
question from:https://stackoverflow.com/questions/65895168/error-in-tolowertxt-non-character-argument-in-r-for-textmining

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is not turning your corpus into a DocumentTermMatrix. The problem lies in your for loop. It turns your corpus into a list of characters.

If you want to use gsub like this, you need to use the content_transformer function.

# removes the need of the for loop and keeps everything in a corpus.
docs <- tm_map(docs, content_transformer(function(x) gsub("
", " ", x)))

This removes the need of the loop and keeps everything as it should be. After this line you can run the rest of your code without any issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...