RTS
RTS

Reputation: 932

Why does this happen? R apply and library functions

Does anyone know why I do not receive output from this command:

library("dplyr", character = T)

Yet, I receive output following this command:

sapply("dplyr", library, character = T)

?

The output looks like this:

     dplyr      
[1,] "dplyr"    
[2,] "stats"    
[3,] "graphics" 
[4,] "grDevices"
[5,] "utils"    
[6,] "datasets" 
[7,] "methods"  
[8,] "base"  

Upvotes: 2

Views: 366

Answers (1)

duckmayr
duckmayr

Reputation: 16920

That's because library() by default invisibly returns the value returned by .packages(),1 so if you call library(), you won't see anything. However, sapply() visibly returns whatever the return value of the calls are. Consider an example:

f <- function(x) invisible(1)
f(1)
sapply(1, f)
# [1] 1

1 From help("library") (kudos to @joran for pointed out this was mentioned in the docs):

Normally library returns (invisibly) the list of attached packages

Upvotes: 3

Related Questions