Escribir líneas de texto en un archivo en R


En el lenguaje de scripting R, cómo escribo líneas de texto, por ejemplo, las siguientes dos líneas

Hello
World

A un archivo llamado " output.txt"?

 270
Author: amarillion, 2010-03-18

10 answers

fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)
 330
Author: Mark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-18 13:54:44

En realidad usted puede hacerlo con sink():

sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()

Por lo tanto hacer:

file.show("outfile.txt")
# hello
# world
 128
Author: aL3xa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-06 18:37:26

Usaría el comando cat() como en este ejemplo:

> cat("Hello",file="outfile.txt",sep="\n")
> cat("World",file="outfile.txt",append=TRUE)

Luego puede ver los resultados de con R con

> file.show("outfile.txt")
hello
world
 96
Author: ps1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-20 10:11:23

¿Qué hay de un simple writeLines()?

txt <- "Hallo\nWorld"
writeLines(txt, "outfile.txt")

O

txt <- c("Hallo", "World")
writeLines(txt, "outfile.txt")
 39
Author: petermeissner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-31 13:34:29

1.Usando argumento de archivo en cat.

 cat("Hello World", file="filename")

2.Use la función sink para redirigir toda la salida de print y cat a file.

 sink("filename")                     # Begin writing output to file
 print("Hello World")
 sink()                               # Resume writing output to console

NOTA: La función print no puede redirigir su salida, pero la función sink sí forzar toda la salida a un archivo.

3.Hacer conexión a un archivo y escribir.

con <- file("filename", "w")
cat("Hello World", file=con)
close(con)
 26
Author: Prateek Joshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-25 01:40:33

Usted podría hacer eso en una sola declaración

cat("hello","world",file="output.txt",sep="\n",append=TRUE)
 11
Author: Charan Raj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-08 16:46:42

Sugiero:

writeLines(c("Hello","World"), "output.txt")

Es más corto y más directo que la respuesta aceptada actual. No es necesario hacer:

fileConn<-file("output.txt")
# writeLines command using fileConn connection
close(fileConn)

Porque la documentación para writeLines() dice:

Si el con es una cadena de caracteres, la función llama a file para obtener una conexión de archivo que se abre durante la duración de la función llamada.

# default settings for writeLines(): sep = "\n", useBytes = FALSE
# so: sep = "" would join all together e.g.
 3
Author: Gwang-Jin Kim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-21 09:20:36

Para completar las posibilidades, puedes usar writeLines() con sink(), si quieres:

> sink("tempsink", type="output")
> writeLines("Hello\nWorld")
> sink()
> file.show("tempsink", delete.file=TRUE)
Hello
World

Para mí, siempre parece más intuitivo usar print(), pero si lo haces la salida no será lo que quieres:

...
> print("Hello\nWorld")
...
[1] "Hello\nWorld"
 2
Author: gung,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-28 23:29:29

Basado en la mejor respuesta:

file <- file("test.txt")
writeLines(yourObject, file)
close(file)

Tenga en cuenta que el yourObject necesita estar en un formato de cadena; use as.character() para convertir si lo necesita.

Pero esto es demasiado escribir para cada intento de guardar. Vamos a crear un fragmento en RStudio.

En Opciones globales > > Código > > Fragmento, escriba esto:

snippet wfile
    file <- file(${1:filename})
    writeLines(${2:yourObject}, file)
    close(file)

Luego, durante la codificación, escriba wfile y presione la pestaña .

 1
Author: Luis Martins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-01 19:22:21

La opción del sistema feo

ptf <- function (txtToPrint,outFile){system(paste(paste(paste("echo '",cat(txtToPrint),sep = "",collapse = NULL),"'>",sep = "",collapse = NULL),outFile))}
#Prints txtToPrint to outFile in cwd. #!/bin/bash echo txtToPrint > outFile
 0
Author: kpie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-21 21:53:16