Output in R, Avoid Writing “[1]”

后端 未结 4 687
独厮守ぢ
独厮守ぢ 2020-12-01 13:35

I use print to output from a function in R, for example:

print(\"blah blah blah\")

This outputs

[1] \"blah bla         


        
相关标签:
4条回答
  • 2020-12-01 14:13

    message is probably the best function to replace print for your needs. cat is also a good function to look at but message will print a new line for you as well. It is also better to use since it is easier to suppress the output from message than it is to suppress the output from cat.

    If you just want to remove the quotes but don't mind the [1] printing then you could use the quote=FALSE option of print.


    Edit: As noted in the comments, message isn't the same as a call to print as it sends the output to a different connection. Using cat will do what you want as others have noted but you'll probably want to add a new line on after your message.

    Example

    cat("This is a message\n") # You'll want to add \n at the end
    
    0 讨论(0)
  • 2020-12-01 14:17

    Use cat("Your string") (type ?cat to see help page) to output concatenated objects to standard output.

    0 讨论(0)
  • 2020-12-01 14:27

    Messing around with print.data.frame may sometimes be useful for custom print methods.

    print(data.frame("message" = "", row.names = "blah blah blah"))
    #                message
    # blah blah blah  
    
    print(data.frame("message" = "blah blah blah", row.names = ""))
    #         message
    #  blah blah blah
    
    0 讨论(0)
  • 2020-12-01 14:29

    If you want to get rid of the [1] only, but preserve the line breaks:

    string_vector <- c('some', 'words', 'in', 'a', 'vector')
    paste(string_vector, collapse = '\n') %>% cat()
    

    produces:

    some
    words
    in
    a
    vector
    
    0 讨论(0)
提交回复
热议问题