Printing newlines with print() in R

后端 未结 4 814
名媛妹妹
名媛妹妹 2020-11-28 23:11

I am trying to print a multiline message in R. For example,

print(\"File not supplied.\\nUsage: ./program F=filename\",quote=0)

I get the o

相关标签:
4条回答
  • 2020-11-28 23:52

    Using writeLines also allows you to dispense with the "\n" newline character, by using c(). As in:

    writeLines(c("File not supplied.","Usage: ./program F=filename",[additional text for third line]))
    

    This is helpful if you plan on writing a multiline message with combined fixed and variable input, such as the [additional text for third line] above.

    0 讨论(0)
  • 2020-11-28 23:58

    An alternative to cat() is writeLines():

    > writeLines("File not supplied.\nUsage: ./program F=filename")
    File not supplied.
    Usage: ./program F=filename
    >
    

    An advantage is that you don't have to remember to append a "\n" to the string passed to cat() to get a newline after your message. E.g. compare the above to the same cat() output:

    > cat("File not supplied.\nUsage: ./program F=filename")
    File not supplied.
    Usage: ./program F=filename>
    

    and

    > cat("File not supplied.\nUsage: ./program F=filename","\n")
    File not supplied.
    Usage: ./program F=filename
    >
    

    The reason print() doesn't do what you want is that print() shows you a version of the object from the R level - in this case it is a character string. You need to use other functions like cat() and writeLines() to display the string. I say "a version" because precision may be reduced in printed numerics, and the printed object may be augmented with extra information, for example.

    0 讨论(0)
  • 2020-11-29 00:17

    You can do this:

    cat("File not supplied.\nUsage: ./program F=filename\n")
    

    Notice that cat has a return value of NULL.

    0 讨论(0)
  • 2020-11-29 00:17

    You can also use a combination of cat and paste0

    cat(paste0("File not supplied.\n", "Usage: ./program F=filename"))
    

    I find this to be more useful when incorporating variables into the printout. For example:

    file <- "myfile.txt"
    cat(paste0("File not supplied.\n", "Usage: ./program F=", file))
    
    0 讨论(0)
提交回复
热议问题