lizzie
lizzie

Reputation: 606

When I try to print using cat, it gives me back NULL in the very end

counts <- c(18,17,15,20,10,20,25,13,12)
outcome <- gl(3,1,9)
treatment <- gl(3,3)

model1 <- glm(counts ~ outcome + treatment, family = poisson())
model2 <- glm(counts ~ outcome, family = poisson())

print_params <- function(model){
  cat("\nAIC:", model$aic,
      "\nDeviance:", model$deviance)}

list_models <- list(model1,model2)
do.call("rbind", sapply(list_models, print_params, simplify = FALSE))

Which gives me:

AIC: 56.76132 
Deviance: 5.129141
AIC: 52.76132 
Deviance: 5.129141NULL

I'm not sure why I'm getting this. Is there another way of doing this?

Upvotes: 1

Views: 604

Answers (2)

alistaire
alistaire

Reputation: 43344

print_params returns NULL (cat is a side effect), so if you look at the results of your *apply, you have the results of cat, then a list of two NULLs. The do.call then returns the results of your function, and then the results of rbinding two NULLs, i.e. one NULL.

To just capture the side effects, simplifying your syntax slightly:

do.call("cat", lapply(list_models, print_params))

gives

AIC: 56.76132 
Deviance: 5.129141
AIC: 52.76132 
Deviance: 5.129141

Upvotes: 3

David
David

Reputation: 610

The NULL is coming from the command line, evaluating what you typed in. This link talks about it (Spacedman's response).

They suggest that you wrap the function with invisible(). This works for me:

invisible(do.call("rbind", sapply(list_models, print_params, simplify = FALSE)))

AIC: 56.76132 
Deviance: 5.129141 

AIC: 52.76132 
Deviance: 5.129141

Upvotes: 1

Related Questions