简体   繁体   English

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

[英]Insert new line with incrementing number between each line of text in R

I am trying to run a script in Rthat gets a load of text, finds the unique lines, lists them and then inserts a new line between each line and sequentially numbers them as follows: 我试图在R中运行一个脚本,该脚本获取大量文本,找到唯一的行,列出它们,然后在每行之间插入新行并按如下顺序对其进行编号:

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

The script I have so far just gets the unique lines 到目前为止,我拥有的脚本仅具有独特的含义

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

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

Please help.....! 请帮忙.....!

Insert new line with incrementing number between each line of text in R 在R中的每一行文本之间插入带有递增编号的新行

How about 怎么样

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

Here I wrote to a different file with a set name. 在这里,我写了一个具有设定名称的文件。

Another similar way: 另一种类似的方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM