在R中的每行文本之间插入一个递增数字的新行

时间:2014-09-29 05:06:05

标签: r

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

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)

请帮助.....!

在R

中的每行文本之间插入一个递增数字的新行

2 个答案:

答案 0 :(得分:3)

怎么样

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

在这里,我写了一个带有设置名称的不同文件。

答案 1 :(得分:2)

另一种类似的方式:

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