Output in R, Avoid Writing "[1]"

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

print("blah blah blah")

This outputs

[1] "blah blah blah"

To the console. How can I avoid the [1] and the quotes?


Solution 1:

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

Solution 2:

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

Solution 3:

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

Solution 4:

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