What is the best way to write to a file some text followed by a data frame? The text is created by pasting variables into strings.
Example desired output:
Here is some text.
This line has a variable: Hello World
Data frame below the line
=================
ID,val1,val2
1,2,3
2,4,6
3,6,9
4,8,12
5,10,15
6,12,18
7,14,21
8,16,24
9,18,27
10,20,30
I can create a string with the initial text:
myvar <- "Hello World"
out_string <- paste0("Here is some text.\n",
"This line has a variable: ", myvar, "\n",
"Data frame below the line\n",
"=================\n")
cat(out_string)
And I can write a dataframe to file:
library(data.table)
mydf <- data.frame(ID = 1:10, val1 = 1:10*2, val2 = 1:10*3)
fwrite(x = mydf,
file = "path/file.txt",
sep = ",",
col.names=T)
But I'm not sure how best to combine these two.
I would think just pasting the data frame onto the end of the out_string
then writing that to file would be best, but my attempts have failed, e.g.
cat(paste0(out_string, mydf, collapse=''))
# Here is some text.
# This line has a variable: Hello World
# Data frame below the line
# =================
# 1:10Here is some text.
# This line has a variable: Hello World
# Data frame below the line
# =================
# c(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)Here is some text.
# This line has a variable: Hello World
# Data frame below the line
# =================
# c(3, 6, 9, 12, 15, 18, 21, 24, 27, 30)
Probably there are a few ways to do this. A simple one is
cat(out_string, file = '/tmp/test.txt')
cat(paste0(colnames(mydf), collapse = ','), file = '/tmp/test.txt', append = T, sep = '\n')
cat(apply(mydf,1,paste0, collapse=','), file = '/tmp/test.txt', append = T, sep = '\n')
and of course, using fwrite
:
cat(out_string, file = '/tmp/test.txt')
fwrite(x = mydf,
file = "/tmp/test.txt",
sep = ",",
col.names=T,
append=T)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With