Is this the expected behavior

My apologies if this is a fuzzy question, as I am new to R. When experimenting with R, I found one strange behavior. When I create a function like:

myfunction <- function(a,b){ print(a,b) } 

and name it like this:

 myfunction(b = 10, a = 20) 

it returns with a result of 20, but if I just call it without a function, assigning it directly to variables like:

 a <- 20 b <- 10 print(a, b) 

I get an error message:

 Error in print.default(a, b) : invalid 'digits' argument 

In addition, I read that printing several variables on one line can be done with:

 sprintf("%i %i",a, b) 

So, is this an error that appears in a function call with the result as the first argument?

+8
source share
1 answer

This may reveal some major differences in how parameters are handled in different scenarios, but I do not consider this a mistake.

If you want to print both values, try changing:

 print(a,b) 

On something like:

 print(paste(a,b)) 

From ?print.default :

 # S3 method for default print(x, digits = NULL, quote = TRUE, na.print = NULL, print.gap = NULL, right = FALSE, max = NULL, useSource = TRUE, …) x the object to be printed. digits a non-null value for digits specifies the minimum number of significant digits to be printed in values. The default, NULL, uses getOption("digits"). (For the interpretation for complex numbers see signif.) Non-integer values will be rounded down, and only values greater than or equal to 1 and no greater than 22 are accepted. ... 

So R expects that everything you really want to print will be contained in the first variable ( x ).

Judging by your results and some comments, it is obvious that in some cases the second variable is taken as the actual value of the digits parameter and in others it is not.

Although this is a bit strange, the more important point is that print(a,b) not a syntactically correct way to print multiple values.

+2
source

Source: https://habr.com/ru/post/1268937/


All Articles