Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 209

6.3.3 Validation of Input

Оглавление

While S3 provides no mechanism to check if all attributes are of the right type, creating an S4 object with the function new() will check if the slots are of the correct type. For example, if we try to create an account while providing a string for the balance (while a number is expected), then R will not create the new object and inform us of the mistake.

# Note the mistake in the following code: my_curr_acc <- new(“CurrAcc”, holder = “Philippe”, interest_rate = 0.01, balance=“0”, # Here is the mistake! branch = “LDN12”, opening_date= as.Date(“2018-12-01”)) ## Error in validObject(.Object): invalid class “CurrAcc” object: invalid object for slot “balance” in class “CurrAcc”: got class “character”, should be or extend class “numeric”

If you omit a slot, R coerces that slot to the default value.

x_account <- new(“CurrAcc”, holder = “Philippe”, interest_rate = 0.01, #no balance provided branch = “LDN12”, opening_date= as.Date(“2018-12-01”)) x_account@balance # show what R did with it ## numeric(0)

The Big R-Book

Подняться наверх