简体   繁体   English

使用 R 中的循环创建 wordcloud output

[英]create wordcloud output using loops in R

I am new to R and currently learning the loop function我是 R 的新手,目前正在学习循环 function

I have many datasets (text files with word and freq in a directory for which I have to make wordcloud.我有很多数据集(我必须为其制作 wordcloud 的目录中包含 word 和 freq 的文本文件。

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.我需要通过读取目录中的每个文本文件来创建一个 wordcloud,并从每个文件中生成一个与文本文件名同名的 png 文件。

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”

No need to write two separate loops, read the data and prepare wordcloud in same loop.无需编写两个单独的循环,读取数据并在同一循环中准备wordcloud

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.根据您的要求将其他参数(如random.order = FALSE )添加到wordcloud function。 ldf would have list of wordclouds. ldf将有 wordclouds 列表。

You defined i as your index for the for-loop.您将i定义为 for 循环的索引。 In this case it is an integer.在这种情况下,它是 integer。 You can't access attributes of integers with $ because they don't have attributes.您不能使用$访问整数的属性,因为它们没有属性。 You can do this only with lists and dataframe.您只能使用列表和 dataframe 执行此操作。

See other Answer for the right way to do wordclouds.请参阅其他答案以了解正确的处理 wordcloud 的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM