簡體   English   中英

使用 R 中的循環創建 wordcloud output

[英]create wordcloud output using loops in R

我是 R 的新手,目前正在學習循環 function

我有很多數據集(我必須為其制作 wordcloud 的目錄中包含 word 和 freq 的文本文件。

目錄名稱循環

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

我需要通過讀取目錄中的每個文本文件來創建一個 wordcloud,並從每個文件中生成一個與文本文件名同名的 png 文件。

代碼到現在

#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”

無需編寫兩個單獨的循環,讀取數據並在同一循環中准備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]])
})

根據您的要求將其他參數(如random.order = FALSE )添加到wordcloud function。 ldf將有 wordclouds 列表。

您將i定義為 for 循環的索引。 在這種情況下,它是 integer。 您不能使用$訪問整數的屬性,因為它們沒有屬性。 您只能使用列表和 dataframe 執行此操作。

請參閱其他答案以了解正確的處理 wordcloud 的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM