使用 R 中的循环创建 wordcloud 输出
create wordcloud output using loops in R
我是 R 的新手,目前正在学习循环函数
我有很多数据集(目录中包含 word 和 freq 的文本文件,我必须为其创建 wordcloud。
目录名循环
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
我需要通过读取目录中的每个文本文件来创建一个词云,并从每个文件生成一个与文本文件同名的 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]])
})
根据您的要求向 wordcloud
函数添加其他参数(如 random.order = FALSE
)。 ldf
会有词云列表。
您将 i
定义为 for 循环的索引。在这种情况下,它是一个整数。您不能使用 $
访问整数的属性,因为它们没有属性。您只能使用列表和数据框执行此操作。
请参阅其他答案以了解制作词云的正确方法。
我是 R 的新手,目前正在学习循环函数
我有很多数据集(目录中包含 word 和 freq 的文本文件,我必须为其创建 wordcloud。
目录名循环
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
我需要通过读取目录中的每个文本文件来创建一个词云,并从每个文件生成一个与文本文件同名的 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]])
})
根据您的要求向 wordcloud
函数添加其他参数(如 random.order = FALSE
)。 ldf
会有词云列表。
您将 i
定义为 for 循环的索引。在这种情况下,它是一个整数。您不能使用 $
访问整数的属性,因为它们没有属性。您只能使用列表和数据框执行此操作。
请参阅其他答案以了解制作词云的正确方法。