如何制作循环

时间:2017-12-20 00:35:17

标签: r for-loop

我想在内容之下创建循环函数。

p1 <- read.table("positive1.txt")
 (wordcount=table(p1))
 palete=brewer.pal(9,"Set1")
 wordcloud(names(wordcount), freq=wordcount, scale=c(5,1),
 rot.per=.12,min.freq=1, random.order=F, random.color=T, colors=palete)

p2 <- read.table("positive2.txt")
 (wordcount=table(p2))
 palete=brewer.pal(9,"Set1")
 wordcloud(names(wordcount), freq=wordcount, scale=c(5,1),
      rot.per=.12,min.freq=1, random.order=F, random.color=T, colors=palete)

p3 <- read.table("positive3.txt")
(wordcount=table(p3))
palete=brewer.pal(9,"Set1")
wordcloud(names(wordcount), freq=wordcount, scale=c(5,1),
      rot.per=.12,min.freq=1, random.order=F, random.color=T, colors=palete)

当我写下面的句子时,我收到了错误信息。

par(mfrow(1,3))
for (i in 1:3) {
p[i] <- readLines(con="positive[i].txt")
p0[i] <- scan("positive[i].txt", character(0), sep = "\n") 
(wordcount[i]=table(p0[i]))
palete=brewer.pal(9,"Set1")
wordcloud(names(wordcount[i]), freq=wordcount, scale=c(5,1),
      rot.per=.12,min.freq=1, random.order=F, random.color=T, colors=palete)
} 

这些是我的错误消息:

Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") : cannot open file 'positive*.txt': Invalid argument

2 个答案:

答案 0 :(得分:2)

考虑lapply p 项目保存到列表中并继续使用read.table()方法:

txt_files <- paste0("positive", 1:3, ".txt")

p <- lapply(txt_files, function(f) {
   tmp <- read.table(f)
   (wordcount=table(tmp))
   palete=brewer.pal(9,"Set1")
   wordcloud(names(wordcount), freq=wordcount, scale=c(5,1),
      rot.per=.12, min.freq=1, random.order=F, random.color=T, colors=palete)
})

答案 1 :(得分:1)

此字符串:paste0("positive", i, ".txt")不会按照您希望的方式进行解释。

请尝试{{1}}。