Search code examples
rloopsvectoratomic

create wordcloud output using loops in R


I am new to R and currently learning the loop function

I have many datasets (text files with word and freq in a directory for which I have to make wordcloud.

Directory name loop

Datasets are a.txt, b.txt, c.txt

Each dataset has the following 2 columns
  name  freq
  Will   45 
  Can    34 
  Good   32 
  Bad    30
  Like   25

I need to create a wordcloud by reading each of the text file in the directory and generate a png file from each file with same name as the text file name.

Code till now

#load libraries
 library(tm)
 library(wordcloud)
 library(SnowballC)
 library(RColorBrewer)

# read all data files in directory
ldf <- list()
listtxt <- dir(pattern = "*.txt")
for (i in 1:length(listtxt)){ldf[[i]] <- read.delim(listtxt[i])}

# generate wordcloud from each file
for (i in 1:length(listtxt)){ldf[[i]] <- wordcloud(listtxt[i$name, i$freq, scale = c(2,.01), 
 random.order = FALSE, colors = brewer.pal(8,"Dark2"])}

It gives an error “$ operator is invalid for atomic vectors”

Solution

  • No need to write two separate loops, read the data and prepare wordcloud in same loop.

    ldf <- lapply(listtxt, function(x) {
             df <- read.delim(x)
             wordcloud::wordcloud(df$name, df$freq)
             #If the column name is not same in all the text files
             #you can also refer columns by their position
             #wordcloud::wordcloud(df[[1]], df[[2]])
    })
    

    Add other parameters (like random.order = FALSE) to wordcloud function based on your requirement. ldf would have list of wordclouds.