【发布时间】:2016-05-25 23:32:43
【问题描述】:
我有正在使用 grep() 操作的文本文件,我想将文件名添加到文本的第一行。我是 R 新手并被卡住了。有什么建议么?谢谢!
【问题讨论】:
我有正在使用 grep() 操作的文本文件,我想将文件名添加到文本的第一行。我是 R 新手并被卡住了。有什么建议么?谢谢!
【问题讨论】:
我不确定您的文本文件的内容应该是什么,但如果该文件有一个有效的注释字符,我建议将它放在文件名的前面。您可以使用readLines 和write 的组合来完成此操作。
首先,您需要使用readLines 读取文件的内容。然后你制作一个文件名的向量,然后是来自readLines 的内容。然后将向量写回它来自的文件。
说实话,最好将其写入不同的文件而不更改您的源材料,但我会让您自己弄清楚您想如何管理它。下面的代码使用临时文件进行说明
#* Create a temporary file
this_file <- tempfile("an_example_file", tmpdir = getwd(), fileext = ".txt")
#* Populate the file with some text
write(LETTERS, this_file)
#* Here's the real start of the solution
file_text <- readLines(this_file)
write(
paste0(
c(sprintf("## %s \n\n", this_file),
file_text)
),
this_file
)
#* see the changes
readLines(this_file)
#* cleanup
file.remove(this_file)
【讨论】:
filename <- 'whatever.txt'
file.text <- readLines(filename)
file.text <- c(filename, file.text) # adds filename to beginning of file.text
fileConn<-file(filename)
writeLines(file.text, fileConn)
close(fileConn)
【讨论】: