Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

suppress comment "joining by..." when running dplyr::left_join

Tags:

r

dplyr

knitr

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

like image 275
Peter Verbeet Avatar asked Mar 20 '15 13:03

Peter Verbeet


1 Answers

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)))
> 
like image 119
mrbcuda Avatar answered Oct 14 '22 23:10

mrbcuda