How to prepend to a file (add at the top)

后端 未结 8 995
逝去的感伤
逝去的感伤 2020-12-20 13:12

Imagine you have a file

sink(\"example.txt\")
data.frame(a = runif(10), b = runif(10), c = runif(10))
sink()

and would want to add some hea

8条回答
  •  旧巷少年郎
    2020-12-20 13:18

    in R there is no need to work with an extra file. You can just do :

    writeLines(c(header,readLines(File)),File)
    

    Yet, using the linux shell seems the most optimal solution, as R is not famous for performant file reading and writing. Especially not since you have to read in the complete file first.

    Example :

    Lines <- c(
    "First line",
    "Second line",
    "Third line")
    File <- "test.txt"
    header <- "A line \nAnother line \nMore line \n\n"
    
    writeLines(Lines,File)
    readLines(File)    
    
    writeLines(c(header,readLines(File)),File)
    readLines(File)
    unlink(File)
    

提交回复
热议问题