Below I create a data frame called c_data. Note that the variable ri has one missing value.

Then I write a function that checks data. One step is to stop the function if ri has missing data. (I removed from the function the syntax not of relevance to my question).

I provide output.

The function performs as expected, except it prints NULL in addition to the expected outcome. Why does it print NULL?

#create data to test function r <- c(.15, .10, NA) N <- c(100, 86, 56) chrvar <- c("a", "b", "c") c_data <- as.data.frame(cbind(r,N, chrvar)) #change variable type from factor to numeric c_data$r <- as.numeric(c_data$r) #change N variable type from factor to integer c_data$N <- as.integer(c_data$N) #change chrvar from factor to character c_data$chrvar <- as.character(c_data$chrvar) str(c_data) myFun <- function(ri= ri, ni=ni, data = data) { #add ri and ni to the data frame named data data$ri <- ri data$ni <- ni #does ri have any missing data num.missing.ri <- 0 for (i in 1:nrow(data)) { if (is.na(data$ri[i] == TRUE)) num.missing.ri = num.missing.ri + 1 } if(num.missing.ri != 0) { print(cat("Number of missing values in ri is", num.missing.ri,"\n")) stop("ri has missing data. myFun is terminated.") } } myFun(ri = r, ni = N, data = c_data) 

This produces this output:

myFun(ri = r, ni = N, data = c_data) ##Number of missing values in ri is 1 ##NULL ## Error in myFun(ri = r, ni = N, data = c_data) : ## ri has missing data. myFun is terminated. 

Why does it print NULL?

3

2 Answers

NULL is printed as this is the return value of cat function. You don't need print and cat.

x <- cat("asdf") x ##NULL print(x) ##NULL 

In your case cat prints the information regarding missing values and then print prints the value returned by cat, which is NULL

FYI: You can make this more efficient, for example:

if(any(ind.na <- is.na(c_data$ri))) stop(paste("ri has", sum(ind.na), "missing values")) 
3

@adibender answered this correctly.

Just do this:

cat("Number of missing values in ri is", num.missing.ri,"\n") 

Or this:

print(paste("Number of missing values in ri is", num.missing.ri)) 

Also, I just wanted to make a note since you are new to functions. When you write your function myFun, you are setting default cases for your variables.

So when you instantiate your function as function(ri = ri, ni = ni, data = data), you're telling R that in the case where the user left out ri, ni, and/or data from their function call, use ri, ni, and/or data instead. This doesn't really make sense for the function unless you have instantiated ri, ni, or data elsewhere.

Instead, you can just write the function as function(ri, ni, data) and R will throw an error if the use leaves these arguments out.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy