Change operator default behavior

Constructive solutions for the default behavior of R are configured for interactive use, but can lead to undesirable behavior in large codebases without much user control. I would be interested to find ways to make the language more rigorous. I have two main examples.

(recirculation) Non-congruent vectors are processed in arithmetic operations:

> x=1:10 > y=1:20 > y=rep(1,20) > x+y [1] 2 3 4 5 6 7 8 9 10 11 2 3 4 5 6 7 8 9 10 11 

Is there a way to make this operation the result of an error?

(conversion) Conversions occur when updating vectors, sometimes changing the type of the updated item, sometimes the type of vector:

 > x[1] <- 'a' > x [1] "a" "2" "3" "4" "5" "6" "7" "8" "9" "10" > x[1] <- 1 > x [1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" 

Is there a way to make this operation the result of an error?

I believe that most of the frustration of new and intermediate users is associated with such behavior (which, in turn, leads to a judging judgment in the language!). Any reference to general recycling and conversion approaches is welcome.

+5
source share
1 answer

For adding. David is right. On reasonable code, I check for such things when the function is in, or at least in the end:

  require(testthat) expect_equal(length(out), length (mainEntry)) 

Conversion is also a very sensitive issue. In the important code, I indicate the type in the assignment:

  X[1] <- as.numeric("a") 

Raises a warning. You can even define classes that prohibit conversions using S4 classes .

Unfortunately, this may not be easy for beginners, but if beginners need to process critical code?

0
source

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


All Articles