14

This is probably straightforward, but I can't find the answer anywhere...

When I use the following code

library("nycflights13")
result <- flights %>% 
    dplyr::select(year:day, hour, origin, dest, tailnum, carrier) %>% 
    dplyr::left_join(airlines)

The following comment is echoed onscreen:

> Joining by: "carrier"

This is certainly useful info to see in interactive sessions, but when I use left_join as part of a longer script, I generally do not want to have this type of comment echoed (especially not when the script generates an html report through knitr, because that html will then also contain a printed Joining by: "carrier" line.

How can I prevent left_join (and the like) to print this comment?

Thanks, Peter

Peter Verbeet
  • 1,786
  • 2
  • 13
  • 29

1 Answers1

15

The comment by @Khashaaa indicates one way to prevent the message, useful and succinct if you know in advance the binding variables. See ?dplyr::join for how to do this with one or more variables. The syntax for the given example would be

left_join(airlines,by="carrier")

Because the dplyr code is using R's message() function to emit the Joining by: * message, you could use R's suppressMessages() wrapper around the left_join (or any other dplyr join) to suppress these messages. See ?message for more info. The OP example in fact returns two kinds of messages,

>library("nycflights13")
>library("dplyr")
>result <- flights %>% 
+    select(year:day, hour, origin, dest, tailnum, carrier) %>% 
+    left_join(airlines)
Joining by: "carrier"
Warning message:
In left_join_impl(x, y, by$x, by$y) :
  joining factor and character vector, coercing into character vector

One can suppress the first message with the suppressMessages() wrapper

>suppressMessages(result <- flights %>% 
+    select(year:day, hour, origin, dest, tailnum, carrier) %>% 
+    left_join(airlines))
Warning message:
In left_join_impl(x, y, by$x, by$y) :
  joining factor and character vector, coercing into character vector

The second message is a diagnostic warning message. See ?warning for more information; there are several ways to handle this case. One way, if you choose to suppress it like the previous message, is to add another wrapper,

> suppressWarnings(suppressMessages(result <- flights %>% 
+         select(year:day, hour, origin, dest, tailnum, carrier) %>% 
+         left_join(airlines)))
> 
mrbcuda
  • 580
  • 7
  • 16
  • In addition to the above answer: even left_join(airlines, on ="carrier") results in the warning message. Unlike most languages, the correct syntax in R is: left_join(airlines, by ="carrier") instead of left_join(airlines, on ="carrier") – LukeXywalker May 05 '22 at 11:02
  • I arrived here trying to combine two tibbles with identical column names. `###_join` spelled out all the column names, which was a bit noisy. In this case, `bind_rows()` did the job and did not produce any warnings. – bovender Mar 13 '23 at 22:01