r Write text and dataframe to file

痞子三分冷 提交于 2019-12-06 05:25:32

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)

Still another way: sink() will open a connection to a file.

sink("<your_new_file_name>")
out_string
df
sink()

One option is to make a connection, which you can write to with both writeLines and write.csv:

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")
mydf <- data.frame(ID = 1:10, val1 = 1:10*2, val2 = 1:10*3)


my_file <- file('file.csv', 'w')

writeLines(out_string, my_file, sep = '')
write.csv(mydf, my_file, quote = FALSE, row.names = FALSE)

close(my_file)

readLines('file.csv')
#>  [1] "Here is some text."                   
#>  [2] "This line has a variable: Hello World"
#>  [3] "Data frame below the line"            
#>  [4] "================="                    
#>  [5] "ID,val1,val2"                         
#>  [6] "1,2,3"                                
#>  [7] "2,4,6"                                
#>  [8] "3,6,9"                                
#>  [9] "4,8,12"                               
#> [10] "5,10,15"                              
#> [11] "6,12,18"                              
#> [12] "7,14,21"                              
#> [13] "8,16,24"                              
#> [14] "9,18,27"                              
#> [15] "10,20,30"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!