在R中的每一行文本之间插入新行,行号递增

在R中的每一行文本之间插入新行,行号递增,r,R,我试图在RTH中运行一个脚本,获取大量文本,找到唯一的行,列出它们,然后在每行之间插入新行,并按如下顺序对它们进行编号: The cat sat on the mat The cat sat on the mat The cat sat on the mat The bat said drat The bat said drat The gnat wore a hat becomes.... >1 The cat sat on the mat >2 The bat said

我试图在RTH中运行一个脚本,获取大量文本,找到唯一的行,列出它们,然后在每行之间插入新行,并按如下顺序对它们进行编号:

The cat sat on the mat
The cat sat on the mat
The cat sat on the mat
The bat said drat
The bat said drat
The gnat wore a hat

becomes....
 >1
 The cat sat on the mat
 >2
 The bat said drat
 >3
 The gnat wore a hat
到目前为止,我的脚本只获得了唯一的行

fileConn<-file("/Users/bilbo/Desktop/output.txt")
longlist <- readLines(file.choose())

lvls1 <- unique(longlist)
writeLines(lvls1, fileConn)
close(fileConn)
View(lvls1)
fileConn怎么样

#Test data
tc<-textConnection("The cat sat on the mat
The cat sat on the mat
The cat sat on the mat
The bat said drat
The bat said drat
The gnat wore a hat")

longlist <- readLines(tc)
close(tc)

fileConn<-file("/Users/bilbo/Desktop/output.txt")
lvls1 <- unique(longlist)
cat(paste0(">", seq_along(lvls1), "\n", lvls1, collapse="\n"), file=fileConn)
close(fileConn)
测试数据 tc另一种类似的方式:

tc <- "The cat sat on the mat
The cat sat on the mat
The cat sat on the mat
The bat said drat
The bat said drat
The gnat wore a hat"

stuff <- unique(scan(text=tc,sep="\n",what="character"))
# for your code:
# stuff <- unique(scan(file="filename.txt",sep="\n",what="character"))
cat(rbind(paste0(">",seq_along(stuff)),stuff),sep="\n")

#>1
#The cat sat on the mat
#>2
#The bat said drat
#>3
#The gnat wore a hat
tc2
#蝙蝠说了一通
#>3
#蚊虫戴着一顶帽子

噢。不,我想先读取一个文件,然后再写入另一个文件,但我想这就是我在file.conn创建新文件和文件时所做的。choose允许我指定要读取的其他文件from@user3632206你是对的。我把我的连接搞糊涂了。这里是
cat
对文件进行写操作。不需要
writeLines
(但如果您愿意,可以使用它)OK。伟大的作为交换——我如何给输出文件起与输入文件相同的名字,但用类似“TBB”的东西来表示它的不同(即它不会覆盖它)?