开发者

Append lines to a file

开发者 https://www.devze.com 2023-04-12 18:01 出处:网络
I\'m new using R. I\'m trying to add (append) new lines to a file with m开发者_C百科y existing data in R. The problem is that my data has about 30000 rows and 13000 cols. I already try to add a line w

I'm new using R. I'm trying to add (append) new lines to a file with m开发者_C百科y existing data in R. The problem is that my data has about 30000 rows and 13000 cols. I already try to add a line with the writeLines function but the resulting file contains only the line added.


Have you tried using the write function?

line="blah text blah blah etc etc"
write(line,file="myfile.txt",append=TRUE)


write.table, write.csv and others all have the append= argument, which appends append=TRUE and usually overwrites if append=FALSE. So which one you want to / have to use, depends on your data.

By the way, cat() can also be used to write text to a file and also has the append= argument.


lapply(listOfVector, function(anyNameofVect){ write(anyNameofVect, file="outputFileName", sep="\t", append=TRUE, ncolumns=100000) })

or

lapply(listOfVector, write, file="outputFileName", sep="\t", append=TRUE, ncolumns=100000)


You can open a connection in append mode to append lines to an existing file with writeLines.

writeLines("Hello", "output.txt") #Create file
CON <- file("output.txt", "a")    #Open connection to append
writeLines("World", CON)          #Append: World
writeLines("End", CON)            #Append: End
close(CON)                        #Close connection

The same but using cat.

cat("Hello\n", file = "output.txt")
cat("World\n", file = "output.txt", append = TRUE)
cat("End", file = "output.txt", append = TRUE)

In case of creating a file and appending subsequent.

CON <- file("output.txt", "w")
writeLines("Hello", CON)
writeLines("World", CON)
writeLines("End", CON)
close(CON)
0

精彩评论

暂无评论...
验证码 换一张
取 消